6

次のコードがあり、保存しているすべてのマーカーが正しく作成されますが、いずれかをクリックすると、最後のインフォウィンドウのみが作成され、どのマーカーをクリックしても最後のマーカーの上にのみ表示されます。私のforループで同じ変数が使用されているので、これには何か関係があると思います。

{% for record in records %}

//need to do the JSON encoding because JavaScript can't have Jinja2 variables
//I need the safe here because Jinja2 tries to escape the characters otherwise
var GPSlocation = {{record.GPSlocation|json_encode|safe}};  
var LatLng = GPSlocation.replace("(", "").replace(")", "").split(", ")
var Lat = parseFloat(LatLng[0]);
var Lng = parseFloat(LatLng[1]);

var markerLatlng = new google.maps.LatLng(Lat, Lng);

var marker = new google.maps.Marker({
    position: markerLatlng,
    title: {{record.title|json_encode|safe}}
});

var infowindow = new google.maps.InfoWindow({
    content: "holding..."
    });

google.maps.event.addListener(marker, 'click', function () {
    infowindow.setContent({{record.description|json_encode|safe}});
    infowindow.open(map, marker);
    });

//add the marker to the map
marker.setMap(map);

{% endfor %}

イベントリスナーを次のように変更してみました。

google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent({{record.description|json_encode|safe}});
        infowindow.open(map, this);
        });

私が見たように、それはSOの他のユーザーには機能しましたが、InfoWindowsは表示されません。ここに明らかなエラーはありますか?

4

1 に答える 1

5

別の関数でマーカーを作成する必要があります。

   // Global var
   var infowindow = new google.maps.InfoWindow();

次に、ループ内:

    var markerLatlng = new google.maps.LatLng(Lat, Lng);
    var title = {{record.title|json_encode|safe}}
    var iwContent = {{record.description|json_encode|safe}}
    createMarker(markerLatlng ,title,iwContent);

ついに:

    function createMarker(latlon,title,iwContent) {
      var marker = new google.maps.Marker({
          position: latlon,
          title: title,
          map: map
    });


google.maps.event.addListener(marker, 'click', function () {
    infowindow.setContent(iwContent);
    infowindow.open(map, marker);
    });

    }

ここで説明します。

于 2012-09-10T16:07:50.147 に答える