Following the sample code from Google Maps API (truncated for brevity) how can I check the marker image failed to load and use a different/default image instead?
var image = {
url: 'https://broken.url.com/no-such-image.png',
size: new google.maps.Size(20, 32),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(0, 32)
};
var marker = new google.maps.Marker({
position: {lat: -33.890542, lng: 151.274856},
map: map,
icon: image,
title: 'Marker demo',
zIndex: 1
});
You can try to use javascript to load the image. If it can be loaded ( onload
event is fired), add marker with image, otherwise ( onerror
event is fired) fallback to something else (for example default marker without image):
var image = new Image();
var image_url = "https://broken.url.com/no-such-image.png";
image.onload = function () {
console.info("Image loaded, adding marker with image !");
var marker = new google.maps.Marker({
position: {lat: -33.890542, lng: 151.274856},
map: map,
icon: {
url: image_url,
size: new google.maps.Size(20, 32),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(0, 32)
},
title: 'Marker demo',
zIndex: 1
});
}
image.onerror = function () {
console.error("Cannot load image, adding marker without image");
var marker = new google.maps.Marker({
position: {lat: -33.890542, lng: 151.274856},
map: map,
title: 'Marker demo',
zIndex: 1
});
}
image.src = image_url;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.