在Google地图上链接XML中的多个标记

时间:2013-05-20 16:52:19

标签: javascript google-maps xml-parsing

我能够从XML文件中提取我的标记并将它们放在Google地图上,但现在我希望每个标记在点击后链接到其各自的网址。有人可以让我知道我做错了什么吗?出于某种原因,我只得到最后一个条目的网址。

downLoad("phpsqlajax.php", function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
        var city = markers[i].getAttribute("city");
        var state = markers[i].getAttribute("state");
        var country = markers[i].getAttribute("country");
        var markerUrl = markers[i].getAttribute("url");
        var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
        var marker = new google.maps.Marker({
            position: point,
            map: googleMap,
            icon: 'map-pin.png',
            url: markerUrl
        });
        google.maps.event.addListener(marker, 'click', function() {
            window.location.href = marker.url;
        });
    }
});

1 个答案:

答案 0 :(得分:0)

制作这样的创建标记功能(未经测试):

function createMarker(point, url) {
    var marker = new google.maps.Marker({
        position: point,
        map: googleMap,
        icon: 'map-pin.png',
        url: markerUrl
    });
    google.maps.event.addListener(marker, 'click', function() {
        window.location.href = marker.url;
    });
}

然后这样称呼:

downLoad("phpsqlajax.php", function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
        var city = markers[i].getAttribute("city");
        var state = markers[i].getAttribute("state");
        var country = markers[i].getAttribute("country");
        var markerUrl = markers[i].getAttribute("url");
        var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
        createMarker(point, markerUrl);
    }
});