我创建的谷歌地图在缩放级别存在问题:当第一个地图出现(页面加载)时,缩放处于国家/地区级别(预期:自动缩放到标记内容)。但是,当我调用
initMap();
重绘内容(无需重新加载页面)时,就会出现预期的边界(不再是国家/地区缩放级别)。
Google 地图正在被调用:
<script async
src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxx&loading=async&libraries=places&callback=initMap">
</script>
JS代码:
let customerList = ....; //JSON object
let map = '';
let markers = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: { lat: 35, lng: -105 },
mapTypeControl: false,
panControl: false,
zoomControl: true,
streetViewControl: false
});
$.each(customerList , function (a, customer) {
geocodeAddress(customer);
});
if (markers.length > 0) {
let bounds = new google.maps.LatLngBounds();
markers.forEach(function (marker) {
bounds.extend(marker.getPosition());
});
map.fitBounds(bounds);
}
}
function geocodeAddress(customer) {
let geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': customer.Address }, function (results, status) {
if (status === 'OK') {
let marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: customer.Name,
icon: markerIcon
});
let infowindow = new google.maps.InfoWindow({
content: `<div><strong>${customer.Name}</strong><br>${customer.Address}</div>`
});
marker.addListener('click', function () {
infowindow.open(map, marker);
});
markers.push(marker);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
所以,这就是我解决这个问题的方法。
出现此问题的原因是
geocode
为 async
,因此最初 markers.length
始终为零:因此 markers.length > 0
始终为 false,并且地图最初不会自行调整。当再次调用时,markers.length > 0
为真,并且发生地图调整。
请参阅下面我更新的代码来考虑这种情况。
请注意,
customer.Adresss
是类似于“300 W 6th St, Austin, TX 78701, United States”的完整地址。
let customerList = ....; //JSON object
let map = '';
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: { lat: 35, lng: -105 },
//Optional
mapTypeControl: false,
panControl: false,
zoomControl: true,
streetViewControl: false
});
let markersList = [];
let promises = [];
$.each(customerList , function (a, customer) {
promises.push(MarkersAux(customer, markersList));
});
Promise.all(promises).then(() => {
if (markersList.length > 0) {
let bounds = new google.maps.LatLngBounds();
$.each(markersList, function (a, marker) {
bounds.extend(marker.position);
});
map.fitBounds(bounds);
}
}).catch(error => {
console.error('Error processing marker:', error);
});
}
async function MarkersAux(customer, markersList) {
return new Promise((resolve, reject) => {
let geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': customer.Adresss }, (results, status) => {
if (status === 'OK') {
let marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: customer.Name,
icon: markerIcon, //Change to the desired icon
});
markersList.push(marker);
resolve(marker);
}
else {
console.error('Geocode was not successful for the following reason:', status);
reject(status);
}
});
});
}