我有一个谷歌地图,它加载没有样式,可能是 1 次刷新中的 30 次,我认为这是我加载地图 json 和地图数据的方式/顺序。我不太确定这样做的最佳方法,因此样式始终存在。我认为这不需要任何异步函数,但不确定。
import MarkerClusterer from '@google/markerclusterer';
const currentPage = $('body').attr('id');
const hasMap = currentPage === 'homePage' || currentPage === 'venuesPage';
let infoArr = [];
let infowindow;
let latLng;
let mapStyles;
let marker;
let markerAddress;
let markerCluster;
let markerCount = -1;
let markerIcon;
let markerInfo;
let markers = [];
let zoomFactor = 4;
$.get('../../data/mapStyles.json').done(data => {
mapStyles = data;
});
$.get('/data/venues.json').done((data) => {
if (hasMap) { // does this need to be hasMap && mapStyles?
initializeMap(data);
}
});
let mcOptions = {
gridSize: 40,
maxZoom: 16,
zoomOnClick: true,
minimumClusterSize: 2,
styles: [
{
height: 53,
url: '/img/meta/m1.png',
width: 53,
},
{
height: 56,
url: '/img/meta/m2.png',
width: 56,
},
{
height: 66,
url: '/img/meta/m3.png',
width: 66,
},
{
height: 78,
url: '/img/meta/m4.png',
width: 78,
},
{
height: 90,
url: '/img/meta/m5.png',
width: 90,
},
],
};
function initializeMap(data) {
if ($(window).width() < 768) {
zoomFactor = 3;
}
let map = new google.maps.Map(document.getElementById('mapContainer'), {
zoom: zoomFactor,
center: new google.maps.LatLng(40.0, -102.0),
styles: mapStyles,
zoomControl: true,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
rotateControl: false,
fullscreenControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
markerIcon = '/img/svgs/icon_map_marker_venue.svg';
data.forEach((venue) => {
let {
lat,
long,
name,
streetAddress,
city,
state,
slug,
} = venue;
if (lat !== '') {
latLng = new google.maps.LatLng(lat, long);
marker = new google.maps.Marker({
position: latLng,
icon: markerIcon,
});
markerAddress = `${streetAddress}<br>${city}, ${state}`;
markerInfo = `<a class="map-marker" href="/venues/venue-detail/index.php?${slug}"><h5>${name}</h5>${markerAddress}</a>`;
markers.push(marker);
infoArr.push(markerInfo);
markerCount += 1;
}
google.maps.InfoWindow.prototype.isOpen = function () {
let map = this.getMap();
return (map !== null && typeof map !== 'undefined');
};
infowindow = new google.maps.InfoWindow({});
google.maps.event.addListener(marker, 'click', (function (marker, markerCount) {
return function () {
if (!infowindow.isOpen()) {
infowindow.setContent(infoArr[markerCount]);
infowindow.open(map, marker);
} else {
infowindow.close();
}
};
}(marker, markerCount)));
});
markerCluster = new MarkerClusterer(map, markers, mcOptions);
}
我做了这样的json,它有效:
$.when($.get('../../data/mapStyles.json').done(styleData => {
mapStyles = styleData;
}), $.get('/data/venues.json').done(vData => {
venueData = vData;
})).then(() => {
initialize(venueData);
});