2013-04-15 4 views
1

Я пытаюсь использовать markerclusterplus.js с Google Maps api v3. Я перебираю массив адресов геокодирования каждого из них и добавляю маркер и информационное окно. Я толкаю маркеры в массиве с именем маркеров и, используя следующий код, чтобы добавить их к моей группеgoogle maps clusterer no markers

var markerCluster = new MarkerClusterer(map, markers);

Нет кластеризованные маркеры не обнаруживаются. Остальная часть кода работает, если добавить

map: map 

моих маркеров они отображаются как стандартные маркеры, так что это все в порядке. При предупреждении массива маркеров с использованием

alert(markers.toString()) 

ничего не возвращается, так что, возможно, ничего не толкается в массив?

Полный код ниже

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&amp;ver=3.5.1"></script> 
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer.js"></script> 

</head> 

<body> 

<script type="text/javascript"> 
var map; //Map variable 
var geocoder; //Geocoder variable 
var infowindow; 
//var marker; //Marker variable 
//Options variable 
var myOptions = { 
       zoom: 2, 
       mapTypeId: google.maps.MapTypeId.ROADMAP, 
       disableDefaultUI: true, 
      }; 
var LatLngList = []; 

//Geocoder function 
function myGeocode() { 

    infowindow = new google.maps.InfoWindow({ 
     maxWidth: 200 
    }); 
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
    geocoder = new google.maps.Geocoder(); 
    var titles = ['Anne of Cleves House', 
     'Lewes Castle', 
     'Michelham Priory', 
     'Fishbourne Roman Palace & Gardens', 
     'Marlipins Museum','The Priest House', 
     'The Long Man' 
     ]; 

    var addresses =[ 
     'Anne of Cleves House, 52, Southover High St, Lewes, BN7 1JA', 
     'Barbican House Museum, 169, High Street, Lewes, BN7 1YE', 
     'Michelham Priory, Upper Dicker, Hailsham, East Sussex, BN27 3QS', 
     'Fishbourne Roman Palace, Roman Way, Fishbourne, West Sussex, PO19 3QR', 
     'Marlipins Museum, High Street, Shoreham-by-Sea, West Sussex, BN43 5DA', 
     'The Priest House, North Lane, West Hoathly, West Sussex, RH19 4PP', 
     'The long man of wilmington' 
    ]; 

    var descriptions = [ 
     'Anne of Cleves House you can explore how the Tudors and Elizabethans lived, worked and relaxed at home.', 
     'Climb to the top of this 1000 year old Norman Castle for stunning panoramic views across Sussex.', 
     'England\'s longest water filled moat surrounds the site which dates back to 1229.', 
     'Welcome to the largest Roman home in Britain', 
     'The striking chequerboard flint and Caen limestone facade is part of one of the oldest Norman buildings in Sussex.', 
     'The only one of its kind open to the public, this beautiful 15th century Wealden hall house stands in a traditional cottage garden.', 
     'the long man of wilmington' 
    ]; 

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

     var address = addresses[i]; 
     var title = titles[i]; 
     var description = descriptions[i]; 
     //var alink = links[i]; 
     var markers = []; 
     var marker; 

     (function(address, title, description) { 

      geocoder.geocode({"address": address }, function(results, status) { 
       if (status == google.maps.GeocoderStatus.OK) { 

        latlng = results[0].geometry.location; 
        LatLngList.push(latlng); 

        map.setCenter(latlng); 

        marker = new google.maps.Marker({ 
         position: latlng 
         //map: map, 
         //title: title, 
        }); 

        markers.push(marker); 

        google.maps.event.addListener(marker, "click", function() { 
         infowindow.setContent("<div class='map-infowindow'><h4 class='gm-title'>"+title+"</h4>"+description+"'<a class='gm-directions' href='http://maps.google.com/maps?saddr="+address+"'>Get directions</a></div>"); 
        infowindow.open(map, marker); 
        }); 

       } 
       else { 
        document.getElementById("text_status").value = status; 
       } 

      });//end of geocoder 
     })(address, title, description); // <- Call function, pass the vars to be captured 
    }//end of for loop 

    alert(markers.toString()) 
    var markerCluster = new MarkerClusterer(map, markers); 

    // Create a new viewpoint bound 
    var bounds = new google.maps.LatLngBounds(); 
    // Go through each... 
    for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) { 
     // And increase the bounds to take this point 
     bounds.extend (LatLngList[i]); 
    } 
    // Fit these bounds to the map 
    map.fitBounds (bounds); 

    //alert(LatLngList.join('\n')) 
} 

window.onload=myGeocode; 
</script> 

<div id="map_canvas" style="width:600px; height:600px;"></div> 

</body> 

</html> 
+0

У вас есть некоторые ошибки в вашем javascript. Предложите вам запустить его через что-то вроде jslint – duncan

ответ

0

Во-первых, вы пересматривают массив маркеров каждый раз в цикле, должны иметь маркеры массив, определенный за пределами цикла.

Во-вторых, геокодер.geocode работает асинхронно, поэтому геокодирование на самом деле не завершено до тех пор, пока цикл не закончится и даже позже не будет вызван вызов alert().

В-третьих, нет необходимости использовать замыкание внутри цикла, так как вы затем каждый раз пересматриваете функцию через цикл. Я всегда предпочитаю в этом случае добавлять частный метод в текущую функцию. Таким образом, функция, выполняющая вызов геокодирования, определяется только один раз и вызывается по мере необходимости. Теперь все, что нам нужно сделать, - это смотреть (с помощью функции обратного вызова геокодера) длина массива маркеров возрастает до тех пор, пока она не будет такой же длины, как массив адресов, и тогда мы знаем, что все геокодирование закончено (при условии, конечно, все прошло хорошо) время для завершения:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&amp;ver=3.5.1"></script> 
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer.js"></script> 
</head> 
<body> 
<script type="text/javascript"> 
var map; //Map variable 
var geocoder; //Geocoder variable 
var infowindow; 
//var marker; //Marker variable 
//Options variable 
var myOptions = { 
       zoom: 2, 
       mapTypeId: google.maps.MapTypeId.ROADMAP, 
       disableDefaultUI: true, 
      }; 
var LatLngList = []; 

//Geocoder function 
function myGeocode() { 
    infowindow = new google.maps.InfoWindow({ 
     maxWidth: 200 
    }); 
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
    geocoder = new google.maps.Geocoder(); 
    var titles = [ 
     'Anne of Cleves House', 
     'Lewes Castle', 
     'Michelham Priory', 
     'Fishbourne Roman Palace & Gardens', 
     'Marlipins Museum','The Priest House', 
     'The Long Man' 
     ]; 

    var addresses =[ 
     'Anne of Cleves House, 52, Southover High St, Lewes, BN7 1JA', 
     'Barbican House Museum, 169, High Street, Lewes, BN7 1YE', 
     'Michelham Priory, Upper Dicker, Hailsham, East Sussex, BN27 3QS', 
     'Fishbourne Roman Palace, Roman Way, Fishbourne, West Sussex, PO19 3QR', 
     'Marlipins Museum, High Street, Shoreham-by-Sea, West Sussex, BN43 5DA', 
     'The Priest House, North Lane, West Hoathly, West Sussex, RH19 4PP', 
     'The long man of wilmington' 
    ]; 

    var descriptions = [ 
     'Anne of Cleves House you can explore how the Tudors and Elizabethans lived, worked and relaxed at home.', 
     'Climb to the top of this 1000 year old Norman Castle for stunning panoramic views across Sussex.', 
     'England\'s longest water filled moat surrounds the site which dates back to 1229.', 
     'Welcome to the largest Roman home in Britain', 
     'The striking chequerboard flint and Caen limestone facade is part of one of the oldest Norman buildings in Sussex.', 
     'The only one of its kind open to the public, this beautiful 15th century Wealden hall house stands in a traditional cottage garden.', 
     'the long man of wilmington' 
    ]; 
    var markers = []; 
    //private function, only need be defined once! 
    function getGeocode(address, title, description) { 
     geocoder.geocode({"address": address }, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       latlng = results[0].geometry.location; 
       LatLngList.push(latlng); 
       map.setCenter(latlng); 
       var marker = new google.maps.Marker({ 
        position: latlng, 
        map: map 
        //title: title, 
       }); 
       markers.push(marker); 
       google.maps.event.addListener(marker, "click", function() { 
        infowindow.setContent("<div class='map-infowindow'><h4 class='gm-title'>"+title+"</h4>"+description+"'<a class='gm-directions' href='http://maps.google.com/maps?saddr="+address+"'>Get directions</a></div>"); 
        infowindow.open(map, marker); 
       }); 
       if (markers.length == addresses.length) { //we have received all of our geocoder responses 
        alert(markers); 
        var markerCluster = new MarkerClusterer(map, markers); 
        // Create a new viewpoint bound 
        var bounds = new google.maps.LatLngBounds(); 
        // Go through each... 
        for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) { 
         // And increase the bounds to take this point 
         bounds.extend (LatLngList[i]); 
        } 
        // Fit these bounds to the map 
        map.fitBounds (bounds); 
       } 
      } else { 
       document.getElementById("text_status").value = status; 
      } 
     });//end of geocoder 
    } 
    for (var i = 0; i < addresses.length; i++) { 
     var address = addresses[i]; 
     var title = titles[i]; 
     var description = descriptions[i]; 
     //var alink = links[i]; 
     //put our private function to work: 
     getGeocode(address, title, description); 
    }//end of for loop 
} 

window.onload=myGeocode; 
</script> 
<div id="map_canvas" style="width:600px; height:600px;"></div> 
</body> 
</html>