如何在从XML文件加载的标记上添加信息窗口

时间:2011-04-08 08:10:30

标签: jquery xml google-maps-api-3

有人可以告诉我如何在从Xml文件加载的标记上添加信息窗口。

这是我用来加载标记的代码。

google.load("maps", "3",  {other_params:"sensor=false"});
google.load("jquery", "1.3.2");

function initialize() {
    var myLatlng = new google.maps.LatLng(52.132633, 5.2912659999999505);
    var myOptions = {
        zoom: 8,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    jQuery.get("locaties.xml", {}, function(data) {
        jQuery(data).find("marker").each(function() {
            var marker = jQuery(this);
            var latlng = new google.maps.LatLng(
                parseFloat(marker.attr("lat")),
                parseFloat(marker.attr("lng"))
            );
            var marker = new google.maps.Marker({position: latlng, map: map});
        });
    });
}
function loadScript() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
    document.body.appendChild(script);
}

window.onload = loadScript;

google.setOnLoadCallback(initialize);

这是XML文件;

<markers>
<marker lat="52.08920341101735" lng="4.279875700000048" />
<marker lat="52.083408210994186" lng="4.314160399999992"/>
<marker lat="52.08598371100446" lng="4.301652100000069"/>
</markers>

1 个答案:

答案 0 :(得分:0)

创建标记后,您需要做的就是分配infowindow:

jQuery.get("locaties.xml", {}, function(data) {
    jQuery(data).find("marker").each(function() {
        var markerXML = jQuery(this);
        var latlng = new google.maps.LatLng(
            parseFloat(markerXML.attr("lat")),
            parseFloat(markerXML.attr("lng"))
        );
        var marker = new google.maps.Marker({position: latlng, map: map});

        // now that the marker is placed, assign event listener on the marker
        // and create/assign infowindow to the event trigger.
        markerInfoWindow(marker, markerXML.attr("info"));
    });
});

// ..... other code here .....

// the marker event handler onclick and infowindow creation/assignment 
function markerInfoWindow(marker, information){
    google.maps.event.addListener(marker, 'click', function(){
        var infowindow = new google.maps.InfoWindow({
            content: information
        });
        infowindow.open(map, marker);
    });
}