简体   繁体   中英

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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