2011-05-02 60 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