[How-to] Use Geotargeting to Display a Visitors Location on a Page


Userlevel 6
  • Former Unbouncer
  • 198 replies

Want to take the personalization of a page to the next level? Maybe you want to display a visitor’s location on the page or pre-fill a city/ region form field.

Now you can using a FREE IP lookup database called GEOLOCATION DB and all it takes is a simple AJAX call and some basic JS. Even better, it’s written for you!

You can see this in action (built in Unbounce) here:
http://unbouncepages.com/geoip-db-location-example/

This also works in both a pop up and a lightbox: http://unbouncepages.com/test-location-convertable/


How to Install in Unbounce

Click Here for Instructions

🚨
This is not an official Unbounce feature. This functionality is based entirely on third party code, and has only been tested in limited applications. Since this isn’t a supported Unbounce feature, our support team will be unable to assist if things go awry. So if you are not comfortable with HTML, Javascript and CSS, please consider consulting an experienced developer.


UPDATE

Step 0

Geolocation DB now requires users to signup in order to use their service. It’s a free signup that will give you a unique API key that must be included in the URL in the code that makes the request to get the location of a visitor.

Once you’ve signed up for a free account you will wan to use the jsonp URL that is provide. It should look something like this:
https://geolocation-db.com/jsonp/[YOUR API KEY]”

Step 1.

Copy this JavaScript and add it to the page “before body end tag”:
REMEMBER TO UPDATE THE URL

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script>
   jQuery.ajax({
    url: "https://geolocation-db.com/jsonp/[YOUR API KEY]",
    jsonpCallback: "callback",
    dataType: "jsonp",
    success: function( location ) {
      var country = location.country_name;
      var region = location.state;
      var city = location.city;
      var lat = location.latitude;
      var long = location.longitude;
      
      // add classes to display location info on page
      //City
      jQuery(".cityText").text(city);
      
      //Region
      jQuery(".regionText").text(region);
      
      //Country
      jQuery(".countryText").text(country);
      
    }
  }); 
</script>

Step 2.

Decide on the text you’d like to use to dynamically display the location information (the AJAX call will make available the country, region, city, latitude, and longitude information from a visitors IP).

Double click the text box and click the “view source” button in the bottom right. Wrap the text you wish to be dynamic with a span and assign the relevant class to display the location information. Here’s a screenshot of what that would look like to display the city info:

####The Default classes for the script are as follows. You can change them if you wish, just be sure to update the javascript to match!

City = "cityText"
Region = "regionText"
Country = "countryText"

Step 3. OPTIONAL Prefill Form Fields with Location Information

You can pre-fill a form field or preselect a dropdown (as long as the option exists) by adding some code to the script. Make sure the ID of your field in the form matches the ID in the code below (you can edit either or both to match):
> $("#cityField").val(city);
> $("#provinceField").val(region);
> $("#countryField").val(country);

Step 4. OPTIONAL Add a Google Map Displaying the Visitors City

Add a custom HTML widget to the page and paste in the following div tag:
<div id="map-container"></div>

Then paste in the following code into the script. Note you can change the size of the map by adjusting the “height” attribute of the iframe:

var frame = '<div class="embed-container maps"><iframe width="100%" height="481px" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?key=AIzaSyBvWSn-wEccZ_YSMG-xW7CfyaecyV1j0uA&q='+city+'+'+region+'" allowfullscreen></iframe></div>'
      
      $("#map-container").html(frame);


Want to take your Unbounce landing pages + Convertables™ to the next level?
:spinbounce: Check out the Ultimate List of Unbounce Tips, Scripts & Hacks


86 replies

@Rob, I can not believe it. It just works! Thanks. Thanks. Thanks!

Hello
I tried at
https://pertodesi.audicaoactiva.pt/loja/
But no results.
Did I miss something?

Thank you

Userlevel 6

Hi @toniomorais it looks to be working for me. Here’s a screenshot: https://www.screencast.com/t/gvio3H7R8rr What are you seeing on the live page?


Could be maybe because i’m in Portugal and database from GeoIP-DB don’t have any data on Portugal?
or I have to change something in script to say that are portuguese cities?

Thank you

Userlevel 6

It is possible that GeoIP-DB doesn’t have data for Portugal. To be honest though I’d be surprised if that were the case as this they have data for much smaller countries. An easy way to test though is to go to this URL https://geoip-db.com/jsonp/ If GeoIP-DB has the data it will display the location information for where you are on the screen in json.

A potential cause could be if you have an internal firewall or proxy server set up from where you are testing from. Anything really that masks or hides your IP could cause issues when testing. Before giving up on this as a possible feature I’d recommend trying to test from different locations in the country. Perhaps you can send the link to some colleagues or friends in different places to see if they get the results?

Hope this helps a bit! Let me know if you have any luck.

Thank you for you suggestions.
This was the result:

callback({“country_code”:“PT”,“country_name”:“Portugal”,“city”:null,“postal”:null,“latitude”:38.7139,“longitude”:-9.1394,“state”:null})

It identifies the country but not the city.

Is there a way to make this work using for example maxmind ? Because I know maxmind shows the Portuguese cities.

Thank you

Userlevel 6

It’s possible that GeoIP-DB simply doesn’t have the city data for the specific IP you’re on other than the region. Although that’s pure speculation on my part. It really depends on what exists in their database which I don’t have direct access to.

It is absolutely possible to make this work with MaxMind, in fact that’s the service I originally created the workaround with. The downside (and the reason I changed it to GeoIP-DB) is that MaxMind is a paid service and you’ll need to register the domain with them before they will allow the API call to go through. If you are ok with paying for their service though I can say that it does work. Another caveat to this though is that I never tested it in Portugal so it’s possible that MaxMind will have the same issue as GeoIP-DB and not have the specific city data for Portugal.

If you do decide to go with MaxMind let me know though and I can DM you the code I originally used as that’s specific to the MaxMind API.

Hello and thank you for the support.

Yes I would like to use the code to use with MaxMind.
I know that Maxmind Have data about Portugal cities.

Thank you

Userlevel 6

Sorry for the delayed reply here @toniomorais. Here’s the original example page I created using MaxMind (it works because unbouncepages.com is registered with their service): http://unbouncepages.com/location-example/

The first step to get it working is to include the maxmind js library via a CDN link. Place this in the head of the page:

<script src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js" type="text/javascript"></script>

Then you can use the following code to apply the location data to the page. See the comments in the code for a more in depth explanation of what each part does:

<script>
  var getCity = function(el) {
    var cityContainer = $(el);
    
    var updateCityText = function (geoipResponse) {
      //get city, if on city available use the default "your city" 
      var cityName = geoipResponse.city.names.en || 'your city';
      
      //get region
      var regionName = geoipResponse.most_specific_subdivision.names.en;
      
      // combine city and region on page
      var city = cityName;
      if (cityName && regionName ) {
            city += ', ' + regionName;
        }
      
      // swap city on page
      cityContainer.text(city);
      
      // optional fill form fields with city value
      $("#city").val(cityName);
      $("#province").val(regionName);
      
      // Google map
      var frame = '<div class="embed-container maps"><iframe width="100%" height="481px" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?key=AIzaSyBvWSn-wEccZ_YSMG-xW7CfyaecyV1j0uA&q='+cityName+'+'+regionName+'" allowfullscreen></iframe></div>'
      
      $("#map-container").html(frame);
         
    };
 
    var onSuccess = function (geoipResponse) {
      updateCityText(geoipResponse);
      console.log(JSON.stringify(geoipResponse, undefined, 4));
    };
    
    // If error show in console
    var onError = function(error) {
      console.log(JSON.stringify(error, undefined, 4));
    };
    geoip2.city(onSuccess, onError);
  };
  
  // Add ID or class of element to swap cit with (i.e. the textbox you'd like to display the location info in)
  getCity(".swap");
  
</script>

Hope this helps getting you started. Let me know here or feel free to direct message me if you hit any snags.

The sample URL looks to not be working correctly and I feel like the script doesn’t work anymore. Can anyone confirm this for me?

Hello,

We have 7 phone numbers (covering 7 world regions) and we would lke to use this to identify what country a visitor is in to show the corresponding phone number.

How would you do this?

Thank you @Rob !!

Userlevel 6

Hi @EthosData! You’d need to write some more code to conditionally display the phone number based on the country. Something like this might work:

if (country == “name of country”) {
// display phone number
} else if (country == “name of other country”) {
// display different phone number
}

The above is just some psuedo code to get you started. You’ll need to target the html that is displaying the phone number and change the content with javascript.

Hope this helps!

Thank you @Rob

Hey @Rob , Just tried this out and as far as I can tell it should be working. Can you take a look and let me know what’s going wrong? I’m really trying to pre-populate zip code into a field but I can’t seem to get even the display text to work. http://specials.zendyhealth.com/test-bed/

Userlevel 6

Hi @Justin_Frech I had a look and there were some syntax errors in the code (a few stray < > and a couple of missing ‘$’). I’ve fixed those for you and saved and it appears to work in Preview. Have a look and if you’re happy you can republish the page.

I just tested it and it thought I was 113 miles away, so maybe not for me 🙂

ok, but there is any way to display a section (not just some small text) only to one country?

thanks

Is it possible to update a button with the user’s location?

For example, a button would read “Request a Demo in {cityText}”

Userlevel 6

Hi @mike22rtn This is an awesome suggestion! It should be possible with some tweaks to the code above to target a button label. It might be tricky to only swap a section of the label due to how the Unbounce builder generated buttons. It would be easier perhaps to use a text link and you can edit the source code directly in the builder and add some <span> tags to target specific text.

A sneaky little workaround to still have it look like a button would be to layer the text link over the button and remove the button’s actual label. To the visitor the text link would still look like the button label.

I’ll try and find some time to add this into the existing workaround in the near future as it shouldn’t be too difficult

Hey @Rob - this is great!

Is there any way to use it to show specific fields? Use case example is GDPR consent check box for EU visitors.

Would love it if we can show/hide this field depending on where visitor is located.

Is there a way to make the “fallback” text say something other than “not found” in the event the script can’t find a city, region or country name?

whoa !

a big thanks for this big tips !!! 😃

I was using this feature successfully for the past couple months. Now my LPs are getting “Mixed Content” errors using this feature.

https://quote.hometownheatingandair.com/furnace-repair/a.html

For what it’s worth, after testing 3 different providers, I’m using ipgeolocation.io, and they’re definitely the best. Everything is SSL

I can’t get this to work on an exit popup. I’m not sure why. Any suggestions?

Reply