【发布时间】:2015-03-28 12:37:46
【问题描述】:
我正在使用Google Maps Store Locator library,但我希望能够在它旁边实现MarkerClusterer。但是,我还没有弄清楚如何让它们一起工作。
代码:
(function($, window, document){
var map = null,
cluster = null;
function storeSource() {
$.extend(this, new storeLocator.StaticDataFeed);
var that = this;
$.getJSON('linktoAJAXThatReturnsJSON', function(data) {
that.setStores(that.parse_(data));
map.fitBounds(centerMap(data));
});
}
storeSource.prototype.parse_ = function(data) {
var stores = [];
data.forEach(function(row){
var
position = new google.maps.LatLng(row.lat, row.long),
locality = row.postcode + ', ' + row.city,
store = new storeLocator.Store(row.id, position, null, {
title : row.name,
address : [row.address, locality, row.country].join('<br>'),
phone : row.phone
});
stores.push(store);
});
return stores;
};
// Clusters Markers together
function makeCluster(data) {
var markers = [];
data.forEach(function(row){
markers.push(row.getMarker());
});
cluster = new MarkerClusterer(map, markers, {});
}
// Finds viewpoint that accomodates all locations
function centerMap(data) {
var bounds = new google.maps.LatLngBounds();
data.forEach(function(row){
bounds.extend(new google.maps.LatLng(row.lat, row.long));
});
return bounds;
}
google.maps.event.addDomListener(window, 'load', function() {
map = new google.maps.Map(document.getElementById('mappanel'), {
mapTypeId : google.maps.MapTypeId.ROADMAP
});
var data = new storeSource();
var view = new storeLocator.View(map, data, {
geolocation: false
});
new storeLocator.Panel(document.getElementById('searchpanel'), {
view: view
});
// I think this is the place to try and add the Markers
// from storeSource. However, debugging shows Markers haven't
// been created yet. This leads me to believe that it's done
// internally in the storeLocator library. Not sure what to do
makeCluster(view.data_.stores_);
});
$(document).on('click', '.action', function(e){
e.preventDefault();
});
})(window.jQuery, window, document);
很遗憾,我没有实时版本。
如代码中所述,MarkerClusterer 需要 google.maps.Marker 类型的对象数组。
我的计划是重用 storeLocator.Store 对象并从中检索标记。我尝试检索它们,但调试显示它们未定义。
不知道如何让这两个库一起工作而不必破解它们中的任何一个。
编辑::取得了一些进展
我能够通过覆盖 storeLocator.View.createMarker 函数将 StoreLocator 使用的标记存储到 MarkerClusterer 中。但是,这会导致另一个问题:标记的可见性由 2 个不同的库控制:MarkerClusterer 想要在缩小时隐藏标记,但 storeLocator 始终显示所有标记。
有没有办法让标记遵循 MarkerClusterer 的默认行为?
我还有一个JFiddle。
编辑#2::解决方案
非常感谢 P1s4 的解决方案!这是修改后的JFiddle。
【问题讨论】:
标签: javascript google-maps-api-3 markerclusterer