简体   繁体   English

如何检测谷歌地图标记图像无法加载提供默认图像?

[英]How to detect google map marker image failed to load to provide default image instead?

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? 按照Google Maps API中的示例代码(为简洁起见截断),如何检查标记图像无法加载并使用其他/默认图像?

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. 您可以尝试使用javascript加载图像。 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): 如果可以加载(触发onload事件),则添加带图像的标记,否则(触发onerror事件)回退到其他东西(例如默认标记没有图像):

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM