简体   繁体   English

Google Maps API V3:简单标记群集未显示

[英]Google Maps API V3: Simple Marker Cluster Not Showing Up

I am developing a Web Based Application using PHP, MongoDB, Javascript, and Google Maps API V3. 我正在使用PHP,MongoDB,Javascript和Google Maps API V3开发基于Web的应用程序。

I was able to easily generate and display markers on a google map by converting the MongoDB array using json_encode. 通过使用json_encode转换MongoDB数组,我能够轻松地在Google地图上生成和显示标记。 Here's an example map with markers and infowindow. 这是带有标记和信息窗口的示例地图。

Markers and InfoWindow 标记和信息窗口

However, when I try to implement the Google Maps MarkerClusterer method, the markers disappears. 但是,当我尝试实现Google Maps MarkerClusterer方法时,标记消失了。 I followed Google Map's " A Simple MarkerClusterer Example " as a guide. 我遵循了Google Map的“ 一个简单的MarkerClusterer示例 ”作为指南。

I also tried declaring a global cluster object, passing it an empty array, 我还尝试了声明全局群集对象,并向其传递了一个空数组,

var markerCluster = new MarkerClustrer(map, markers);

then using markerCluster.addMarkers(markers, true); 然后使用markerCluster.addMarkers(markers, true); as alternate method with no luck. 作为没有运气的替代方法。

It seems pretty simple but somehow, it is not displaying the markers. 看起来很简单,但是不知何故,它没有显示标记。 I also tried commenting out the whole infoWindow/OnClick event section so I don't think its related to that. 我还尝试注释掉整个infoWindow / OnClick事件部分,因此我认为它与此无关。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

PHP MongoDB Query: PHP MongoDB查询:

<?php

// Connect to Mongo and set DB and Collection
try
{
    $mongo = new Mongo();
    $db = $mongo->selectDB('twitter');
    $collection = $db->selectCollection('tweets');
}
catch(MongoConnectionException $e)
{
    die("Failed to connect to Twitter Database ". $e->getMessage());
}

// The hotspots array will contain the data that will be returned
$tweets = array();

// Return a cursor of tweets from MongoDB
$cursor = $collection->find();

// Try catch for catching whether there are tweets to display
$count = 0;
try 
{
    $count = $cursor->count();
} 
catch (MongoCursorException $e) 
{
    die(json_encode(array('error'=>'error message:' .$e->getMessage())));
}

// Loops through the cursor again specifically for querying all geo locations
// Unlike table display of tweets, this cursor is not limited by pages. 
foreach($cursor as $id => $value)
{ 
    $mapLocations[] = array
    (
        'id'=>$value['_id'],
        'screen_name'=>$value['screen_name'],
        'name'=>$value['name'],
        'tweet'=>$value['tweet'],
        'hashtags'=>$value['hashtags'],
        'lat'=>$value['geo']['lat'],
        'long'=>$value['geo']['long'],
        'date'=>$value['date'],
        'img'=>$value['img'],
        'specImg'=>$value['specImg']
    );
}
// var_dump($mapLocations);
?>

Javascript Function: JavaScript函数:

function initialize() 
{
    // Converts MongoDB information to JSON, ready for Javascript
    var tweets = <?php echo json_encode($mapLocations); ?>;

    // Sets google maps options
    var myOptions = 
    {
        // Centers on Maui...
        center: new google.maps.LatLng(20.80362, -156.321716),
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };

    // Sets Marker Clusterer Options
    var mcOptions =
    {
        gridSize: 50, maxZoom: 15
    };

    // Generates Google Map and applies the defined options above.
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    // Infowindow for displaying information for onClick event  
    // Content must be inside the google.maps.event function 
    // Otherwise the same content will be entered on all markers    
    var infoWindow = new google.maps.InfoWindow({});

    var markerCluster = null;   // Initializes markerCluster
    var markers = [];           //Array needed to pass to MarkerClusterer

    // Loops through each tweet and draws the marker on the map.    
    for (var i = 0; i < tweets.length; i++)
    {
        var tweet = tweets[i];

        if(tweet.lat != null || tweet.long != null) 
        {
            var myLatLng = new google.maps.LatLng(tweet.lat, tweet.long);
            //document.write(" Latitude: " + tweet.lat + " Longitude: " + tweet.long + " <br> ");
            var marker = new google.maps.Marker({ 
                position: myLatLng,
                //icon: "markers/flag.png",
                //map: map,
            });

            markers.push(marker);

            google.maps.event.addListener(marker, 'click', (function(marker, i) 
            {
                return function() 
                {
                    // Generates a table for infoWindow
                    var content = "<table class='popup'>";

                    // Check if image exits, otherwise show no image icon
                    if(tweets[i].specImg != null) 
                    {
                        content += "<tr><th width=75 ><a href=" + tweets[i].specImg + ">";
                        content += "<img height=75 width=75 src=" + tweets[i].specImg + "></a>";
                    }
                    else
                    {
                        content += "<tr><th width=75><img height=75 width=75 src=images/noimage.jpg>";
                    }
                    // Concatanate screen name and tweet
                    // Will work on trimming information
                    content += "</th><td>" + tweets[i].screen_name + " says...<br>"; 
                    content += "''" + tweets[i].tweet +  "''<br>";
                    content += "on " + tweets[i].date + "</td>";
                    content += "</table>";

                    // Zoom into marker on click
                    map.setZoom(15);
                    map.setCenter(marker.getPosition());

                    // Sets the infoWindow content to the marker
                    infoWindow.setContent(content);
                    infoWindow.open(map, marker);
                }
            })(marker, i)); 
        }
    } 
    var markerCluster = new MarkerClusterer(map, markers);
}

@Robbie: @罗比:

The JSONned $mapLocations becomes a multidimensional array but I simplified the $mapLocations to only store a 2D lat and long. JSONned $ mapLocations变为多维数组,但我简化了$ mapLocations以仅存储二维经度和纬度。 The javascript source code becomes as follow. javascript源代码如下。

var tweets = [{"lat":20.87179594,"long":-156.47718775},{"lat":20.87195633,"long":-156.47714356},{"lat":20.87138419,"long":-156.47719744},{"lat":21.3320704,"long":-157.8685716},{"lat":null,"long":null},{"lat":21.36509415,"long":-157.92824454},{"lat":21.3320825,"long":-157.8684742},{"lat":null,"long":null},{"lat":21.33673131,"long":-157.86824},{"lat":21.332507,"long":-157.86635342},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":37.36520709,"long":-121.92386941},{"lat":37.2499758,"long":-121.86462506},{"lat":37.36278955,"long":-121.90521146},{"lat":null,"long":null},{"lat":37.36278955,"long":-121.90521146},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":20.88944108,"long":-156.4761887},{"lat":37.36273157,"long":-121.90479984},{"lat":20.85102618,"long":-156.65936351},{"lat":20.88949978,"long":-156.4762491},{"lat":null,"long":null},{"lat":21.3320168,"long":-157.8685715},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":null,"long":null}];

FINALLY FIGURED IT OUT: 最终得出结论:

As I expected, it was something very simple. 如我所料,这很简单。 Apparently you need to download the markerclusterer.js file from the Google Maps Utility Library . 显然,您需要从Google Maps Utility Library下载markerclusterer.js文件。 I thought the clusterer was already built in into the API itself. 我认为集群器已经内置在API本身中。

I fixed it by downloading the script into server and referencing it like so 我通过将脚本下载到服务器并像这样引用它来修复它

<script type="text/javascript" src="markerclusterer.js"></script>

Anyways, thanks everyone for the help! 无论如何,谢谢大家的帮助!

I think there may be a couple of issues: 我认为可能存在两个问题:

  1. The infowindow is required per marker, you are sharing one infowindow for all the markers and repeatedly changing its contents. 每个标记都需要信息窗口,您要为所有标记共享一个信息窗口,并重复更改其内容。

  2. Also check that you don't fall into the closure trap. 还要检查您没有落入封闭陷阱。 I could retpye it all, but you basically need to create a function out of the closure. 我可以全部重写,但是基本上您需要在闭包之外创建一个函数。 There is an explination of how to do this at http://www.robertbolton.com/blog/google-maps-v3-multiple-markers-and-infowindows-in-a-loop 有关如何执行此操作的说明,请访问http://www.robertbolton.com/blog/google-maps-v3-multiple-markers-and-infowindows-in-a-loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM