2016-10-14 6 views
3

Я пытаюсь помещать InfoWindow в несколько маркеров, сгруппированных с MarkerClusterer, но без успеха. Я могу генерировать только карты с infowindows OR с кластером; не оба одновременно. Поиск через веб-делает меня более запутать ....Интеграция Google Maps MarkerClusterer с infowindow

Точка старта была google developers page: с моими потребностями, я создал следующий код:

<div id="map"></div> 
    <script> 

     function initMap() { 

     var map = new google.maps.Map(document.getElementById('map'), { 
      zoom: 5, 
      center: {lat: -15.7942357, lng: -47.8821945} 
     }); 

     // Add some markers to the map. 
     // Note: The code uses the JavaScript Array.prototype.map() method to 
     // create an array of markers based on a given "locations" array. 
     // The map() method here has nothing to do with the Google Maps API. 
     var markers = locations.map(function(location, i) { 
      return new google.maps.Marker({ 
      position: location, 
      }); 
     }); 

     // Add a marker clusterer to manage the markers. 
     var markerCluster = new MarkerClusterer(map, markers, 
      {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'}); 
     } 
     var locations = [ 
    {lat: -19.9286,  lng: -43.93888}, 
    {lat: -19.85758, lng: -43.9668}, 
    {lat: -18.24587, lng: -43.59613}, 
    {lat: -20.46427, lng: -45.42629}, 
    {lat: -20.37817, lng: -43.41641}, 
    {lat: -20.09749, lng: -43.48831}, 
    {lat: -21.13594, lng: -44.26132}, 
     ] 
    </script> 
    <script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"> 
    </script> 
    <script async defer 
    src="https://maps.googleapis.com/maps/api/js?callback=initMap"> 
    </script> 

Тогда я купируюсь здесь. Код, показанный в InfoWindow, вызывает другие объекты, чем «местоположения». Больше, чем я пытаюсь, худшие результаты ...

Я хотел бы добавить только простую информацию для КАЖДОГО маркера: только название и уникальный веб-ссылки на маркер.

Может кто-нибудь помочь?

+0

Там нет попытки создать InfoWindow в размещенном коде. – geocodezip

ответ

7

Добавьте «уникальную информацию» для каждого маркера в ваш массив местоположений (например, ответ на этот вопрос:).

Добавьте каждого маркера, который открывает InfoWindow с этим уникальным контентом.

var infoWin = new google.maps.InfoWindow(); 
var markers = locations.map(function(location, i) { 
    var marker = new google.maps.Marker({ 
    position: location 
    }); 
    google.maps.event.addListener(marker, 'click', function(evt) { 
    infoWin.setContent(location.info); 
    infoWin.open(map, marker); 
    }) 
    return marker; 
}); 

proof of concept fiddle

фрагмент кода:

function initMap() { 
 

 
    var map = new google.maps.Map(document.getElementById('map'), { 
 
    zoom: 5, 
 
    center: { 
 
     lat: -15.7942357, 
 
     lng: -47.8821945 
 
    } 
 
    }); 
 
    var infoWin = new google.maps.InfoWindow(); 
 
    // Add some markers to the map. 
 
    // Note: The code uses the JavaScript Array.prototype.map() method to 
 
    // create an array of markers based on a given "locations" array. 
 
    // The map() method here has nothing to do with the Google Maps API. 
 
    var markers = locations.map(function(location, i) { 
 
    var marker = new google.maps.Marker({ 
 
     position: location 
 
    }); 
 
    google.maps.event.addListener(marker, 'click', function(evt) { 
 
     infoWin.setContent(location.info); 
 
     infoWin.open(map, marker); 
 
    }) 
 
    return marker; 
 
    }); 
 

 
    // Add a marker clusterer to manage the markers. 
 
    var markerCluster = new MarkerClusterer(map, markers, { 
 
    imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' 
 
    }); 
 

 
} 
 
var locations = [{ 
 
    lat: -19.9286, 
 
    lng: -43.93888, 
 
    info: "marker 1" 
 
}, { 
 
    lat: -19.85758, 
 
    lng: -43.9668, 
 
    info: "marker 2" 
 
}, { 
 
    lat: -18.24587, 
 
    lng: -43.59613, 
 
    info: "marker 3" 
 
}, { 
 
    lat: -20.46427, 
 
    lng: -45.42629, 
 
    info: "marker 4" 
 
}, { 
 
    lat: -20.37817, 
 
    lng: -43.41641, 
 
    info: "marker 5" 
 
}, { 
 
    lat: -20.09749, 
 
    lng: -43.48831, 
 
    info: "marker 6" 
 
}, { 
 
    lat: -21.13594, 
 
    lng: -44.26132, 
 
    info: "marker 7" 
 
}, ]; 
 

 
google.maps.event.addDomListener(window, "load", initMap);
html, 
 
body, 
 
#map { 
 
    height: 100%; 
 
    width: 100%; 
 
    margin: 0px; 
 
    padding: 0px 
 
}
<script src="https://maps.googleapis.com/maps/api/js"></script> 
 
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script> 
 
<div id="map"></div>

+0

Отлично. Работала очень хорошо. Благодарю. –

+0

Второй вопрос: Я пытаюсь создать разные маркеры на основе категорий/типов. В основном, будут только 2 цветных маркера (красный и зеленый - или что-то другое). На основе [страницы разработчика Google] (https://developers.google.com/maps/documentation/javascript/custom-markers#customizing_markers_by_map_features), но у меня нет необходимости в создании функции, которая вызывает «тип», в каждом месте. Я могу только изменить значки globaly, добавив «icon:» file.png «» после «position: location». –

+0

Один вопрос на вопрос. – geocodezip