带有多个标记/模态的Google Maps API

时间:2014-06-16 21:57:56

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

我正在使用具有数百个标记的Google Maps API JS v.3。我想打开一个模式,其中包含特定于他们点击的标记的信息。我打算使用PHP和AJAX从MySQL数据库中获取模态数据,但我不确定如何确定用户点击的标记......

非常感谢任何帮助

`

        var map;

        //icon variables
        /*
        var dem = 'path/to/blue/icon.png';
        var rep = 'path/to/red/icon.png';
        var oth = 'path/to/grey/icon.png';
        */
        var locations = [

            <?php
              $c = 0;
              $nr = mysqli_num_rows($gethouses);
              while($z = mysqli_fetch_array($gethouses)):
            ?>
            ['<?php echo $z['name_first'].' '.$z['name_last']; ?>', <?php echo $z['lat']; ?>, <?php echo $z['lng']; ?>, 4],
            <?php

              $c++;
              endwhile;
            ?>
        ];

        var map = new google.maps.Map(document.getElementById('google_world_map'), {
            zoom: 10,
            center: new google.maps.LatLng(39.675, -119.98),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

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

        var marker, i;
        var markers = new Array();

        for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });

        markers.push(marker);

        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
            }
            })(marker, i));
        }

        function AutoCenter() {
        // Create a new viewpoint bound
        var bounds = new google.maps.LatLngBounds();
        // Go through each...
        $.each(markers, function (index, marker) {
        bounds.extend(marker.position);
        });
        // Fit these bounds to the map
        map.fitBounds(bounds);
        }
        AutoCenter();

        </script>`

1 个答案:

答案 0 :(得分:0)

您可以在marker对象中添加自定义参数(理想情况下该值应该是唯一的)。

for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map,
        custom_param: some_unique_value
    });

    ....
}

然后,在您的标记click事件中,您可以通过获取此案例marker.custom_param中的值来确定点击了哪个标记。

google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
        infowindow.setContent(locations[i][0]);
        infowindow.open(map, marker);

        // make use of `marker.custom_param`
        var myCustomParam = marker.custom_param;
    }
    })(marker, i));
}