回调函数不工作

callback function not working

本文关键字:工作 函数 回调      更新时间:2023-09-26

我创建了一个脚本,根据您单击鼠标的区域在地图上放置标记。一旦放置了标记,当鼠标悬停在标记上时,就会出现一个信息框,其中包含标记的放置地址。然而,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);

它不会将返回值存储在任何位置,只是被丢弃了。