I use async await to render map, with pseuode-code like this
In HTML, simple:
<div class="site-branch-offices">
<div id="map" style="width:100%;height:65vh;"></div>
</div>
Then, this is the data that I got form server:
{
"country": {
"lat": -2.548926,
"lng": 118.0148634
},
"branches": [
[
{
"lat": -6.1490383,
"lng": 106.8831949
},
"Jakarta"
],
[
{
"lat": -7.2196698,
"lng": 112.7307977
},
"Surabaya"
]
]
}
Here is the code to init google map with js:
let map;
async function fetchData() {
let url = '/branch-office/fetch-branch';
try {
let response = await fetch(url);
return await response.json();
} catch (error) {
console.log(error);
}
}
function renderMap(data) {
new google.maps.Map(
document.getElementById("map"),
{
center: {lat: data.country.lat, lng: data.country.lng},
zoom: 5,
gestureHandling: "cooperative"
}
);
// // Create an info window to share between markers.
const infoWindow = new google.maps.InfoWindow();
data.branches.forEach(([position, title], i) => {
// For debug
console.log("position", position);
console.log("title", title);
console.log("i", i);
const marker = new google.maps.Marker({
position,
map,
title: `${i + 1}. ${title}`,
label: `${i + 1}`,
optimized: false,
});
// Add a click listener for each marker, and set up the info window.
marker.addListener("click", () => {
infoWindow.close();
infoWindow.setContent(marker.getTitle());
infoWindow.open(marker.getMap(), marker);
});
});
}
async function initMap() {
await (fetchData())
.then(data => {
renderMap(data);
})
}
window.initMap = initMap;
All is render successfully, except the marker. Any suggestion is appreciated.