如何显示基于地理位置的动态图像?

How to display a dynamic image based on geo location?

我正在尝试根据用户访问我网站时所在的国家/地区显示特定图像。我设法使用 ajax 和 https://geolocation-db.com/jsonp/ 来捕获位置信息。

如果我从美国或任何其他国家/地区检查这个,我可以输出该国家/地区(使用 TunnelBear),但我的目标是根据输出国家/地区显示不同的图像。

我错过了什么?

//get ip, city, state & country
$.ajax({
    url: "https://geolocation-db.com/jsonp",
    jsonpCallback: "callback",
    dataType: "jsonp",
    success: function (location) {
        $("#country").html(location.country_name);
    },
});

let getCountry = location.country_name;

if (getCountry == 'United States') {
    bg.innerHTML = `<img src="https://via.placeholder.com/900x450?text=UNITED STATES">`;
} else if (getCountry == 'United Kingdom') {
    bg.innerHTML = `<img src="https://via.placeholder.com/900x450?text=UNITED KINGDOM">`;
} else {
    bg.innerHTML = `<h3>This is not working!</h3>`;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

        <div id="country"></div>
        <div id="bg"></div>

您需要在成功方法中检查国家。

//get ip, city, state & country
$.ajax({
    url: "https://geolocation-db.com/jsonp",
    jsonpCallback: "callback",
    dataType: "jsonp",
    success: function (location) {
      $("#country").html(location.country_name);
      let getCountry = location.country_name;

      if (getCountry == 'United States') {
          bg.innerHTML = `<img src="https://via.placeholder.com/900x450?text=UNITED STATES">`;
      } else if (getCountry == 'United Kingdom') {
          bg.innerHTML = `<img src="https://via.placeholder.com/900x450?text=UNITED KINGDOM">`;
      } else {
          bg.innerHTML = `<h3>This is not working!</h3>`;
      }
    },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="country"></div>
<div id="bg"></div>