将数据存储在googlemap标记的其他字段中

时间:2013-12-28 20:54:33

标签: javascript google-maps google-maps-api-3

我正在使用google maps api和javascript,我不太熟悉。这是我用来在地图上绘制标记的代码。我从我的数据库中获得了纬度和经度:

    var geocoder;
    var map;
    var jsonStr = '<?php echo json_encode($arajka) ?>';
    var LatLong = JSON.parse(jsonStr);
    function initialize() {
        geocoder = new google.maps.Geocoder();
        var mapOptions = {
          center: new google.maps.LatLng(50.000001, 20.000001),
          zoom: 12
        };
        map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
        var marker = [];

        for(var i=0;i<LatLong.length;i++){

           var LatLong1 = new google.maps.LatLng(LatLong[i].lat, LatLong[i].lon);
        marker.ajdi=LatLong[i].id; // storing additional data (I need to get it when user clicks on certain marker)
           marker.push(new google.maps.Marker({position: LatLong1, map: map, title: LatLong[i].login}));

        }
                    // trying to set some listener but it fails.
        google.maps.event.addListener(marker, 'click', function() {
            map.setZoom(8);
            map.setCenter(marker.getPosition());
            alert("ASDASDASD" + marker.ajdi);
        });
    }

所以,这位聆听者并不工作,我不知道为什么。好吧,我希望它并不完全知道它是什么标记。当我尝试用一​​个单独的那个,就像在教程中,它工作正常。我有这个阵列时我不知道该怎么办。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您的代码中有几个错误:

  1. 正如@Hollister所提到的,marker是一个数组,所以你需要将addListener调用放在循环中;

  2. 您必须将其他标记数据存储到标记中,而不是存储到标记数组中;

  3. 您必须在监听器中使用this,而不是marker

    for(var i=0;i<LatLong.length;i++){
    
       var LatLong1 = new google.maps.LatLng(LatLong[i].lat, LatLong[i].lon);
       var this_marker = new google.maps.Marker({position: LatLong1, map: map, title: LatLong[i].login});
       this_marker.ajdi=LatLong[i].id; // storing additional data (I need to get it when user clicks on certain marker)
       marker.push(this_marker);
    
                // trying to set some listener but it fails.
       google.maps.event.addListener(this_marker, 'click', function() {
           map.setZoom(8);
           map.setCenter(this.getPosition());
           alert("ASDASDASD" + this.ajdi);
       });
    }