2011-05-02 56 views
5

好吧,用戶選擇國家,然後通過自動填充小部件選擇他們居住的地區,城市和地區。他們選擇的值被連接成一個地址應該用來調用Google Maps API並顯示一個標記地址的地圖...不幸的是,這是行不通的...我在Firebug中得到這個異常:顯示顯示所選地址的谷歌地圖

未捕獲的異常:[Exception。 ... 「組件返回失敗代碼: 0x80004005(NS_ERROR_FAILURE) [nsIDOMViewCSS.getComputedStyle]」 nsresult:「0x80004005 (N S_ERROR_FAILURE)」的位置: 「JS 框架:: http://maps.gstatic.com/intl/en_us/mapfiles/api-3/4/11a/main.js ::值Xk ::第55行」 的數據:無]

這裏是我的代碼:

與此src="http://maps.google.com/maps/api/js?sensor=false"

var address = selectedArea + ', ' + selectedCity + ', ' + selectedDistrict + ', Lebanon'; 

var geocoder = new google.maps.Geocoder(); 
geocoder.geocode({ 'address': address }, function (results, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
     var map = new google.maps.Map($("#addressMap")); 
     map.setCenter(results[0].geometry.location); 
     var marker = new google.maps.Marker({ 
      map: map, 
      position: results[0].geometry.location 
     }); 
    } else { 
     alert("Geocode was not successful for the following reason: " + status); 
    } 
}); 
腳本標籤

那是怎麼回事?

回答

22

當你創建地圖對象時,你給了一個jQuery對象,但它除了一個DOM對象。嘗試DOM對象本身。

我還添加了一些選項,縮放級別和地圖類型。

下面是最終代碼:

var address = selectedArea + ', ' + selectedCity + ', ' + selectedDistrict + ', Lebanon'; 

var geocoder = new google.maps.Geocoder(); 
geocoder.geocode({ 'address': address }, function (results, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
     var mapOptions = { zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP }; 
     var map = new google.maps.Map(document.getElementById('addressMap'), mapOptions); 
     map.setCenter(results[0].geometry.location); 
     var marker = new google.maps.Marker({ 
      map: map, 
      position: results[0].geometry.location 
     }); 
    } else { 
     alert("Geocode was not successful for the following reason: " + status); 
    } 
}); 
+0

完美!按照我想要的方式工作!謝謝:) – Kassem 2011-05-03 06:50:18

+0

我的印象是document.getElementById('addressMap')等價於$('div#addressMap')。顯然不是。感謝您的幫助。 – 2012-10-22 21:17:53

+1

@AdamWaite'document.getElementById()'返回一個DOM對象,'$()'返回一個jQuery對象。 – 2012-10-23 08:08:46