Dynamically Change Page Content Based on a User’s Location

January 8, 2015 | by

Let’s say you would like to dynamically change the phone number on a landing page depending on where a user is located. For example, if the person is in California you would like to show them the phone number for your California office on your landing page, but if they are in Japan you would like to show them the phone number for the Japanese office.

show-nearest-office-san-mateo

One way to implement this is using JavaScript and the HTML5 Geolocation API. The benefit of this approach is we can create one landing page and dynamically change it based on a user’s location, instead of multiple static landing pages.

Here is a demo of a landing page, where we show the phone number for the closest Marketo office to the user. We’ll walk through the technical implementation details below.

We create an object for office locations with latitude and longitude coordinates, and a second object with office phone numbers. In production, it would be a better practice to combine these two objects into a single object.

We create a method to request a user’s location. To handle errors, if the user’s location is not accessible, we will default to Marketo’s headquarters and its phone number.

Lastly, we’ll create a method to find the closest office to the user’s location, and then return the phone number for the closest office on the page. This method uses the findNearest method from Geolib, which is JavaScript library that provides geospatial operations.

Here’s the full implementation. We trigger the getLocation method when the user clicks the button on the page.

This GitHub repo has files needed to set up this demo.