0

我的问题是这个。我是 javascript 新手。我有一个函数可以异步调用 Google 地图 API(根据 latlng 返回位置)。我的代码中的这个函数是MarkerCreaterPlusLocation。此调用返回我在代码中名为MarkerCreater的另一个函数中需要的值。但问题是MarkerCreater不会停止MarkerCreaterPlusLocation返回值。

为了克服这个问题,我尝试在异步函数返回值时使用MarkerCreater的回调来执行

结构如下:

google.maps.event.addListener(map, 'click',addLatLng); //This code attaches the function to Listener



function addLatLng(event) {
        path = poly.getPath();
        path.push(event.latLng);
        MarkerCreaterPlusLocation(event.latLng,MarkerCreater);//MarkerCreater is the callback function
}




function MarkerCreaterPlusLocation(input,callback){
    location="l";
    geocoder.geocode({'latLng': input}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[1]) {
        location=results[1].formatted_address;
        callback(location,input);//I call the callback function upon the success of the result or otherwise
      } else {
        location="l"; 
        callback(location,input);
      }
    } else {
      location="l";
      callback(location,input);
    }
    });
}




function MarkerCreater(l,x){

    var marker = new google.maps.Marker({
        position: x,
        title: '#' + path.getLength()+l,
        icon: 'images/beachflag.png',
        map: map
});
    ///Some more javascript code 
}

我想我在这里犯了错误,因为这似乎不起作用。相反,它给出了一个 404 错误,这使我更难以理解它。请帮忙

4

1 回答 1

3

您的location变量没有用 声明var,这意味着它在全局范围内(即窗口)。因此,设置location实际上是设置window.location,这导致重定向到 404。

要解决此问题,请将 MarkerCreaterPlusLocation 函数的第一行更改为:

var location="l";

这将仅在函数范围内创建它,而不是在窗口中创建它。

于 2013-11-06T14:43:29.083 回答