【问题标题】:Difficulties to pass a parameter in callback function (Google Map API Markers)难以在回调函数中传递参数(Google Map API Markers)
【发布时间】:2026-02-02 06:40:01
【问题描述】:

我的代码有问题。确实,我正在尝试将数组的值作为参数提供,但在回调函数中,我得到的值是“未定义”。

我的目标是根据地点类别 (catLieu) 和地点类型 (typeLieu) 创建自定义标记。它适用于类别,但我对类型有困难。

这是我的代码(其中的一部分):

var catLieu;
var typeLieu;
var education =['school', 'university'];

function performSearch() {
clearMaps();
var i;

var clickedEducation = [];
for (i=0;i<education.length;i++)
{
    var checkEducation=document.getElementById(education[i])
    if (checkEducation.checked)
    {
        clickedEducation.push(education[i])
    }
}

if (clickedEducation.length>0)
{
    var caseEdu=[];
    var lieuEdu='Education';
    for (var j=0;j<clickedEducation.length;j++)
            {
                caseEdu[j]=clickedEducation[j];
                var request = {
                    bounds: maCarte.getBounds(), 
                    types: caseEdu[j] // IT DOESN'T WORK
                };
                console.log
                service.radarSearch(request, function (results,status) {callbackExecute(results,status,callback,lieuEdu,caseEdu[j])}); // IT DOESN'T WORK
            }

}



function callbackExecute(results,status,fonctionDeRetour,catPlace,typePlace)
{
    fonctionDeRetour(results,status,catPlace,typePlace);
}



function callback(results, status, catPlace, typePlace) 
{

    if (status != google.maps.places.PlacesServiceStatus.OK) 
    {
        alert(status); //Message d'alerte zéro résultat
        return;
    }

    catLieu=catPlace;
    typeLieu=typePlace; 

    for (var i = 0, result; result = results[i]; i++) 
    {
        createMarker(result); // Créer un marqueur pour chaque résultat
    }
    catLieu="";

}
}

编辑:我写了“var caseEdu[];”但不是我的问题的根源。

EDIT2:问题已解决,非常感谢Dr.Molle :)

【问题讨论】:

  • 打开您的 Web 控制台(它位于浏览器菜单中的某处,或按 F12 或 Ctrl+Shift+I [在 Mac 上为 Cmd+Shift+I] 并在开发工具中选择控制台),然后您会发现语法错误:var caseEdu[]; is invalid JavaScript。更正语法错误后很可能还有其他问题,但在发布 SO 问题之前,请确保代码确实解析。
  • 我打开了控制台,但没有错误,但代码不起作用,因为回调函数中的 'typePlace' 未定义,并且 types: caseEdu[j] 也未定义。我看到它感谢调试模式下的断点
  • 如果代码完全运行,那么代码不是您问题中的代码。再次重申:问题中的代码存在语法错误,根本不会运行
  • 编辑:你是对的,但这是因为我在复制代码时犯了一个错误。在我的真实代码中,我有“var caseEdu=[]”,但它不起作用我原谅“=”抱歉 :)
  • 使用问题上的“编辑”链接修复它。不要告诉我你重新输入了所有的代码?!为什么不使用复制粘贴并避免浪费每个人的时间(尤其是您的时间)?从问题中删除所有代码,然后使用 copy-and-paste 将代码粘贴到其中。(如果需要,请先通过jsbeautifier.org 运行它)。

标签: javascript arrays google-maps-api-3 callback google-maps-markers


【解决方案1】:

在执行radarSearch-callback的那一刻,外层循环已经结束,j指向caseEdu的末尾。

可能的修复:

替换这一行:

service.radarSearch(request, function (results,status) {callbackExecute(results,status,callback,lieuEdu,caseEdu[j])});

与....

(function(edu){
   service.radarSearch(request, 
                       function (results,status) {
                         callbackExecute(results, 
                                         status, 
                                         callback, 
                                         lieuEdu, 
                                         edu);
                       }); 
 })(caseEdu[j]);

....现在循环中的当前项将作为参数传递


演示:

var catLieu;
var typeLieu;
var education = ['school', 'university'];

function clearMaps() {
  var markers = maCarte.get('markers');

  markers.forEach(function(marker) {
    marker.setMap(null);
  });
  markers.clear();
}

function performSearch() {
  clearMaps();
  var i;

  var clickedEducation = [];
  for (i = 0; i < education.length; i++) {
    var checkEducation = document.getElementById(education[i])
    if (checkEducation.checked) {
      clickedEducation.push(education[i])
    }
  }

  if (clickedEducation.length > 0) {
    var caseEdu = [];
    var lieuEdu = 'Education';
    for (var j = 0; j < clickedEducation.length; j++) {
      caseEdu[j] = clickedEducation[j];
      var request = {
        bounds: maCarte.getBounds(),
        type: caseEdu[j] // IT DOESN'T WORK
      };
      (function(edu) {
        service.radarSearch(request, function(results, status) {
          callbackExecute(results, status, callback, lieuEdu, edu)
        });
      })(caseEdu[j]);
    }

  }



  function callbackExecute(results, status, fonctionDeRetour, catPlace, typePlace) {
    fonctionDeRetour(results, status, catPlace, typePlace);
  }



  function callback(results, status, catPlace, typePlace) {

    if (status != google.maps.places.PlacesServiceStatus.OK) {
      //alert(status); //Message d'alerte zéro résultat
      return;
    }

    catLieu = catPlace;
    typeLieu = typePlace;

    for (var i = 0, result; result = results[i]; i++) {
      createMarker(result); // Créer un marqueur pour chaque résultat
    }
    catLieu = "";

  }
}

function createMarker(result) {
  maCarte.get('markers').push(new google.maps.Marker({
    position: result.geometry.location,
    map: maCarte
  }))
}

function initialize() {


  var mapOptions = {
    zoom: 12,
    center: new google.maps.LatLng(52.5498783, 13.425209099999961),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    noClear: true,
    markers: new google.maps.MVCArray
  };
  maCarte = new google.maps.Map(document.getElementById('map_canvas'),
    mapOptions);
  service = new google.maps.places.PlacesService(maCarte)
  maCarte.controls[google.maps.ControlPosition.TOP_CENTER]
          .push(document.getElementById('ctrl'));
  google.maps.event.addListenerOnce(maCarte,'idle',performSearch);
}

google.maps.event.addDomListener(window, 'load', initialize);
html,
       body,
       #map_canvas {
         height: 100%;
         margin: 0;
         padding: 0
       }
       label {
         display: block;
       }
       #ctrl {
         background: #fff;
       }
<div id="map_canvas">
  <div id="ctrl">
    <label for="school">
      <input id="school" type="checkbox" onchange="performSearch()" />school</label>
    <label for="university">
      <input checked  id="university" type="checkbox" onchange="performSearch()" />university</label>
  </div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places"></script>

【讨论】:

  • 非常感谢您的帮助,它有效!我决定使用数组,因为当回调将被执行时,循环已经完成,所以我不能使用简单的字符串,但我没有想到caseEdu[j] 不能工作的事实同样的原因。你解决了我的问题,非常感谢:)
  • 我只是明白我不需要你的解决方案的数组一个字符串caseEdu就足够了(不需要caseEdu[]