0

我有一个简单的谷歌地图 v3 代码。它创建地图并向markerCluster 添加一个标记。一切正常,除了将内容设置到 infoWindow 并打开它。该函数getSupplierDetails()只返回一个短字符串(即“Red Supply”)。

这就是问题所在:如果我将文本“Red Supply”硬编码到 setContent 行,infoWindow.setContent("Red Supply");那么信息窗口会随着内容正常打开。

但是,如果我将其保留在下面的代码中,则信息窗口根本不会打开,尽管该getSupplierDetails()函数返回“红色供应”。

getSupplierDetails()函数返回此 JSON 字符串: {"popupContent": "Red Suppplier"}来自 Firebug。

花了这么长时间没有任何解决方案。任何帮助表示赞赏。

谢谢

var map;
var markerCluster;
var infoWindow;

$(document).ready(function() {

  if (mapElem != null) {
        var latlng = new google.maps.LatLng(54.664936, -2.706299);
        var myOptions = {
            zoom: 5,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
        };

        map = new google.maps.Map(mapElem, myOptions);
        markerCluster = new MarkerClusterer(map);
        infoWindow = new google.maps.InfoWindow();

    AddMarkers();
  }
});

function AddMarkers(){
    markerCluster.clearMarkers();
    var marker = new google.maps.marker({position:latLng, map:map, title:"title"});

    google.maps.event.addListener(marker, 'click', function() {
      var res = getSupplierDetails();
      infoWindow.setContent(res);
      infoWindow.open(map, this);
    });

    markers.push(marker);
    markerCluster.addMarkers(markers);
}


function getSupplierDetails() { //returns {"popupContent": "Red Suppplier"}
    $.ajax({
        type: 'POST',
        url: "sitedetail.aspx",
        dataType: 'json',
        timeout: 30000,
        success: function(data) {
            return data.popupContent;
        },
        error: function(xhr, textStatus, thrownError) {
            var resp = JSON.parse(xhr.responseText);
            alert(resp.message);

        }
    });
}
4

2 回答 2

0
function getSupplierDetails() { // returns "Red Suppplier" or ""
    var content = '';
    $.ajax({
        type: 'POST',
        url: "sitedetail.aspx",
        dataType: 'json',
        timeout: 30000,
        success: function(data) {
            content = data.popupContent;
        },
        error: function(xhr, textStatus, thrownError) {
            var resp = JSON.parse(xhr.responseText);
            alert(resp.message);

        }
    });
    return content;
}
于 2011-06-24T15:19:46.527 回答
0

ajax 成功调用是异步的,这就是你得到 null 的原因,你所做的很好(将 SetContent 移动到成功部分)但你也可以这样做

google.maps.event.addListener(marker, 'click', function() {
  getSupplierDetails(function(res){
     infoWindow.setContent(res)
  });
  infoWindow.setContent(res);
  infoWindow.open(map, this);
});

function getSupplierDetails(callback) {
    $.ajax({
        type: 'POST',
        url: "sitedetail.aspx",
        dataType: 'json',
        timeout: 30000,
        success: function(data) {
            callback(data.popupContent);
        },
        error: function(xhr, textStatus, thrownError) {
            var resp = JSON.parse(xhr.responseText);
            alert(resp.message);

        }
    });
}
于 2011-11-16T04:01:57.133 回答