谷歌地图 API Javascript;类型错误 a 为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22315807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google Maps API Javascript; TypeError a is null
提问by user3223207
var map;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(25.825421, 0.898438),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
google.maps.event.addListeneer(map, 'click', function(x) {
ylat.value = x.latLng.lat();
ylong.value = x.latLng.lng();
});
}
var ylat = document.getElementById('lat');
var ylong = document.getElementById('loong');
function addMarker() {
var lat = ylat.value;
var loong = ylong.value;
if(!lat || !loong) return;
var coordinate = new google.maps.LatLng(lat, loong);
var marker = new google.maps.Marker({
map: map,
position: coordinate
});
}
google.maps.event.addDomListener(document.getElementById('search'), 'click', addMarker);
google.maps.event.addDomListener(window, 'load', initialize);
When I run this on Firefox, Firebug tells me "TypeError: a is null" I have looked this up on various websites and on here as well. I don't have the slightest clue on how to fix it. Please help!
当我在 Firefox 上运行它时,Firebug 告诉我“TypeError: a is null”我已经在各种网站和这里查找过这个。我对如何修复它一无所知。请帮忙!
回答by Dr.Molle
There are 2 issues with this line:
这条线有两个问题:
google.maps.event.addDomListener(document.getElementById('search'), 'click', addMarker);
the function.addMarker
is not available in global scope(and not at the time when this line will be executed)- (I guess that's the problem here)assuming the script is placed inside the
<head/>
, the elements inside the<body/>
are not available yet,document.getElementById('search')
will benull
.
该函数。addMarker
在全局范围内不可用(并且在执行此行时不可用)- (我想这就是这里的问题)假设脚本放置在 中
<head/>
, 中的元素<body/>
尚不可用,document.getElementById('search')
将是null
.
Moving the line to the end of initialize should fix both problems.
将行移动到 initialize 的末尾应该可以解决这两个问题。
Additionally, there is a typo:
另外,还有一个错别字:
google.maps.event.addListeneer(map, 'click', function(x) {
//__________________________^