JavaScript 使用 Google 地图 API 检查文件是否存在

javascript checking if file exists with google maps api

本文关键字:文件 是否 存在 检查 API 使用 Google 地图 JavaScript      更新时间:2023-09-26

我正在尝试检查并查看是否存在图像,以便我可以相应地调整我的contentString。但是,当我尝试执行此操作时,地图上只显示一个图钉(第一个)。

  var checkins = <?php echo $json; ?>;
  function imageExists(url, callback) {
    var img = new Image();
    img.onload = function() { callback(true); };
    img.onerror = function() { callback(false); };
    img.src = url;
  }
  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: {lat: 39.8282, lng: -98.5795}
    });
    setMarkers(map);
  }
  function setMarkers(map) {
    var infowindow = new google.maps.InfoWindow({
      content: ""
    });
    for (var i = 0; i < checkins.length; i++) {
      var checkin = checkins[i];
      var marker = new google.maps.Marker({
        position: {lat: parseFloat(checkin[2]), lng: parseFloat(checkin[3])},
        map: map,
        title: checkin[1]
      });
      var imageUrl = 'http://rjbogz.ddns.net/pictures/'+checkin[0]+'.jpg';
      imageExists(imageUrl, function(exists) {
        if (exists){
          contentString = '<b>'+checkin[6]+'</b><br><b>'+checkin[4]+'</b> by <b>'+checkin[5]+'</b><br>At <b>'+checkin[1]+'</b><br><img src="pictures/'+checkin[0]+'.jpg" style="width:300px;height:300px;">';
          bindInfoWindow(marker, map, infowindow, contentString);
        } else {
          contentString = '<b>'+checkin[6]+'</b><br><b>'+checkin[4]+'</b> by <b>'+checkin[5]+'</b><br>At <b>'+checkin[1]+'</b>';
          bindInfoWindow(marker, map, infowindow, contentString);
        }
      });
    }
  }
  function bindInfoWindow(marker, map, infowindow, description) {
      marker.addListener('click', function() {
          infowindow.setContent(description);
          infowindow.open(map, this);
      });
  }

正如您在imageExists函数中看到的那样,我尝试添加检查以查看图像是否存在,但随后它只在地图上绘制了一个图钉。该网站目前已发布到 http://rjbogz.ddns.net/map.php 如果您想看看它的外观。我想修复的一个例子是,如果您单击百慕大的图标(没有与之关联的图像文件)。

你已经很接近了,if (ImageExists(image) != 0) {只有几个问题

首先,您已将函数声明为 ImageExist ,因此您需要修复该拼写错误。 其次,您可能希望将if(ImageExists(image) != 0) {更改为if(ImageExists(image)) {,因为您的函数将返回布尔值。

最后,您的contentString中有一些未关闭的 HTML。

对代码进行这些调整应该可以修复它,它看起来像这样:

if (ImageExist(image)) {
    contentString = '<b>'+checkin[6]+'</b><br><b>'+checkin[4]+'</b> by <b>'+checkin[5]+'</b><br>At <b>'+checkin[1]+'</b><br><img src="pictures/'+checkin[0]+'.jpg" style="width:300px;height:300px;">';
} else {
    contentString = '<b>'+checkin[6]+'</b><br><b>'+checkin[4]+'</b> by <b>'+checkin[5]+'</b><br>At <b>'+checkin[1]+'</b>';
}

您可以在此处看到它在JS小提琴中工作:https://jsfiddle.net/igor_9000/ts9udgn7/4/

还有一个更新的小提琴,显示它处理来自 placehold.it 的图像:https://jsfiddle.net/igor_9000/ts9udgn7/6/

希望对您有所帮助!