回调函数不工作
callback function not working
我创建了一个脚本,根据您单击鼠标的区域在地图上放置标记。一旦放置了标记,当鼠标悬停在标记上时,就会出现一个信息框,其中包含标记的放置地址。然而,infobox没有显示,因为当我调用"info_text"时,它返回未定义的结果。我意识到我需要添加一个回调函数,但我认为我没有正确实现它。有人能帮我修复代码吗?感谢
我的代码:
var geocoder;
function initialize()
{
geocoder = new google.maps.Geocoder();
var event = google.maps.event.addListener;
// intializing and creating the map.
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
event(map,'click',function(e){
var marker = placeMarker_and_attachMessage(e.latLng,map,count);
count = count + 1;
});
} // end of initalize.
function placeMarker_and_attachMessage(position,map)
{
var event = google.maps.event.addListener;
var message = ['This', 'is', 'the', 'secret', 'message'];
var marker = new google.maps.Marker({
position: position,
map: map
});
var pos = info_text(position);
alert('pos is: ' + pos);
var infowindow = new google.maps.InfoWindow({
content: 'hello'
});
event(marker,'mouseover',function(){
infowindow.open(map,this);
});
event(marker,'mouseout',function(){
infowindow.close();
});
} // end of function.
function info_text(position)
{
var lat = parseFloat(position.lat());
var lng = parseFloat(position.lng());
alert('lat,lng is: ' + (lat,lng));
var latlng = new google.maps.LatLng(lat,lng);
alert('just before geocode');
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
alert('in info_text If statement');
if(results[1])
{
alert('in inner if statement');
var finalResult = myCallback(results[1].formatted_address);
return finalResult;
}
else
{
alert('no results found');
}
}
else
{
alert('could not pinpoint location');
}
});
}
function myCallback(loc)
{
alert('i have a location!');
return loc;
}
google.maps.event.addDomListener(window, 'load', initialize);
您的函数info_text
没有return
,所以这一行:
var pos = info_text(position);
其中pos
未定义。
您需要包括:
return something;
在你的功能中的某个时刻(就像你在下面做的那样)。
已添加函数myCallback
返回一个值,但返回的位置是:
myCallback(results[1].formatted_address);
它不会将返回值存储在任何位置,只是被丢弃了。
相关文章:
- 咖啡的Javascript订单总数无法使函数正常工作.请协助
- removeClass函数没有'工作不正常
- 你能解释一下这个阶乘函数是如何工作的吗?
- JavaScript链接在点击时不起作用;函数在页面加载时工作
- jQuery加载的async和ready函数不工作
- 更改智能表中的页面将停止JQuery函数的工作
- 为什么不是'我的函数在解析云代码中工作吗?当我在Angular和Express中测试时,它是有效的
- jQuery函数不能只在一个页面上工作
- 如何检查这个代码点火器php函数是否工作,该函数是否在ajax url中使用
- 从js引擎的角度来看闭包和构造函数是如何工作的
- appendChild在函数外部工作,但在函数内部不工作
- 如何在php中创建一个函数,该函数与文本区域一起工作,通过输入类似[color:red]的内容来打印具有等效颜色的文本
- 由于某种原因,我的JavaScript函数无法工作
- 为什么递归生成器函数没有't在ES2015工作
- 我需要一个jQuery函数来只工作在700px以上的屏幕大小,无法在我的代码中发现错误
- 从控制台中的工作函数转换为工作脚本.(请参阅编辑)
- Angular JS-工作函数中的“错误:[$interpole:interr]Can't interpole:
- 简化工作函数以替换特定单词
- 为什么不在回调中工作函数?
- InnerHTML不工作:函数未定义