Skip to content

Instantly share code, notes, and snippets.

@MikeiLL
Last active March 23, 2024 23:32
Show Gist options
  • Save MikeiLL/05bbe8b5e5249769748d1eb609c46c5d to your computer and use it in GitHub Desktop.
Save MikeiLL/05bbe8b5e5249769748d1eb609c46c5d to your computer and use it in GitHub Desktop.
import {Loader} from '@googlemaps/js-api-loader';
class Map {
constructor() {
this.$el = document.querySelectorAll('.acf-map');
this.map = null;
this.loader = new Loader({
apiKey: 'my_key',
version: 'weekly',
});
this.$el.forEach($el => {
this.initMap($el);
})
}
async initMap($el) {
const $markers = $el.querySelectorAll('.marker');
const mapOptions = {
zoom: parseInt($el.dataset.zoom) || 16,
mapTypeId: 'roadmap',
mapId: 'JAGLETS_MAP_ID',
};
await this.loader.load();
this.map = new google.maps.Map($el, mapOptions);
this.map.markers = [];
const markerPromises = [];
$markers.forEach($marker => {
markerPromises.push(async () => this.initMarker($marker, this.map));
});
const results = await Promise.allSettled(markerPromises);
for (const result of results) {
let marker = await result.value();
this.map.markers.push(marker);
}
this.centerMap(this.map);
}
async initMarker($marker, map) {
const lat = parseFloat($marker.dataset.lat);
const lng = parseFloat($marker.dataset.lng);
const latLng = {lat, lng};
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
const marker = new AdvancedMarkerElement({
position: latLng,
map: map,
});
if ($marker.innerHTML) {
const infowindow = new google.maps.InfoWindow({
content: $marker.innerHTML,
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
return marker;
}
async centerMap(map) {
const bounds = new google.maps.LatLngBounds();
map.markers.forEach(marker => {
bounds.extend({
lat: marker.position.lat,
lng: marker.position.lng,
});
});
if (map.markers.length === 1) {
map.setCenter(bounds.getCenter());
} else {
map.fitBounds(bounds);
}
}
};
const map = new Map();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment