Skip to content
Advertisement

How to display a dynamic image based on geo location?

I’m trying to display a specific image based on the country the user is visiting my site from. I’ve managed to use ajax and the https://geolocation-db.com/jsonp/ to capture the location information.

If I check this from the US, or any other country, I’m able to output that country (using TunnelBear), but my goal is to display a different image depending on the output country.

What am I missing?

//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>

Advertisement

Answer

You need to check the country inside the success method.

//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>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement