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

时间:2016-08-29 12:51:28

标签: javascript google-maps google-maps-api-3

根据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
});

1 个答案:

答案 0 :(得分:3)

您可以尝试使用javascript加载图片。如果可以加载(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;