Hands on

Detect Location with a Web Browser and Reverse Geocode it to an Address with HERE

By Nic Raboy | 08 November 2018

Have you ever wondered how certain websites or businesses are able to track you from your computer web browser and then target you with certain advertisements or content that you may or may not actually want? A lot of times you’re being tracked by the general location of your IP address, but there are other circumstances where you’ve probably given permission through one of those browser notifications.

With simple JavaScript, most modern web browsers are able to prompt for permission to access your location where the location is a latitude and longitude coordinate that is more accurate than you might think. However, a latitude and longitude coordinate isn’t always the most useful to a lot of users.

We’re going to see how to get the users current location from the web browser and reverse geocode it to the nearest address using the HERE Reverse Geocoder API.

Finding the Browser Latitude and Longitude with HTML5 and JavaScript

There aren’t any requirements beyond basic JavaScript to get the HTML Geolocation API functional in a project. The only requirement is to have a web browser that supports it. Lucky for us, most browsers support it as of now.

Create a new index.html file somewhere on your computer and include the following:

<html>
    <head>
        <title>Browser Location</title>
    </head>
    <body>
        <script type="text/javascript">
            if(navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(position => {
                    console.log(position.coords);
                });
            } else {
                console.error("Geolocation is not supported by this browser!");
            }
        </script>
    </body>
</html>

The magic here is actually in the JavaScript. First we check to make sure the current web browser supports the HTML Geolocation API. If it does not, we’re going to throw an error in the logs. If the API is supported we’re going to get the current position and print the coordinates to the logs.

When running this code, the user will be prompted for permission in their web browser. If permission is granted, you’ll have a latitude and longitude to work with.

We’re going to take this to the next level with HERE.

Reverse Geocoding a Latitude and Longitude Position with HERE

To use the HERE APIs you’ll need a free developer account. Create a project within your developer account and maintain a copy of the app id and app code associated with the JavaScript and REST APIs.

Within the index.html file, we need to include two scripts:

<script src="https://js.api.here.com/v3/3.0/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.0/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>

With the HERE JavaScript libraries included in the project, the HERE Location Services (HLS) platform can be initialized:

var platform = new H.service.Platform({
    "app_id": "APP-ID-HERE",
    "app_code": "APP-CODE-HERE"
});

You’ll want to swap out the app_id and app_code with those found in your developer dashboard. With the platform initialized, the geocoder needs to be initialized and it can be done with the following:

var geocoder = platform.getGeocodingService();

To reverse geocode something, all we need is the latitude and longitude coordinates, which we have from the HTML Geolocation API. The actual process of reverse geocoding with HERE looks like the following:

geocoder.reverseGeocode(
    {
        mode: "retrieveAddresses",
        maxresults: 1,
        prox: latitude + "," + longitude
    }, data => {
        alert("The nearest address to your location is:\n" + data.Response.View[0].Result[0].Location.Address.Label);
    }, error => {
        console.error(error);
    }
);

A lot of possible information comes back with every request to the API. We only care about the label for this example which includes as much information as the API found. For example, with coordinates, the label would have the street address, city, state, and country. Information may vary depending on the country where the result resides.

The final code might look something like this:

<html>
    <head>
        <title>Browser Location</title>
    </head>
    <body>
        <script src="https://js.api.here.com/v3/3.0/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>
        <script src="https://js.api.here.com/v3/3.0/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            var platform = new H.service.Platform({
                "app_id": "APP-ID-HERE",
                "app_code": "APP-CODE-HERE"
            });
            var geocoder = platform.getGeocodingService();
            if(navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(position => {
                    geocoder.reverseGeocode(
                        {
                            mode: "retrieveAddresses",
                            maxresults: 1,
                            prox: position.coords.latitude + "," + position.coords.longitude
                        }, data => {
                            alert("The nearest address to your location is:\n" + data.Response.View[0].Result[0].Location.Address.Label);
                        }, error => {
                            console.error(error);
                        }
                    );
                });
            } else {
                console.error("Geolocation is not supported by this browser!");
            }
        </script>
    </body>
</html>

The code above uses plain HTML and vanilla JavaScript to accomplish the task. It wasn’t necessary to use any frameworks like jQuery, Angular, React.js, or Vue.js to get the job done.

Conclusion

You just saw how to detect the users coordinate location within the web browser and then convert those latitude and longitude coordinates into an address using the HERE Reverse Geocoder API for JavaScript. This could be useful in your web applications for numerous reasons beyond just advertising purposes. For example, you could develop a heat map for certain cities using your application and create priorities based on the results. Of course with a little imagination, you could come up with much better use cases than the one mentioned.