How to show the user it's location in your website
Tags: webdev, javascript, tutorial, api
Published: 2022-06-03 06:51:14

No we are not building a location tracker to spy on the users , but why don't we generously show them where they live ?

We can make use of <mark>OpenLayers</mark> and <mark>Geoapify</mark> to display a map with the city of the user in focus .

[OpenLayers](https://openlayers.org/) is a JS library makes it easy to put a dynamic map in any web page ,  is completely free, Open Source JavaScript, released under the 2-clause BSD License (also known as the FreeBSD).

[Geoapify](https://geoapify.com/) API makes it extremely easy for us to find the user's location i.e. approximate latitude and longitude and the user's city , country and other info.

------------

The The <mark>IP Geolocation API</mark> provided by Geoapify detects the user's location by IP address and then returns a `.json` file with all the details that could be found out from just the I.P. address of the user like it's country of residence , currency , phone code, postal code , language etc.This has some better use cases like determining  which language the visitor speaks, which currency to use in payment forms and more data.
But we shall keep it simple and pretend that we track our users .

To use this API we need to register as a user on the Geoapify website , they have a free tier available which has enough feature to build our application . After registering with whatever method suits you ,

1. Go to the Dashboard
2. Create a new project and name it whatever you want
3. On the left side bar , go to the API keys section
4. Choose the type of App as IP Geolocation API as this is the API we will be using 
5. Generate a API key 

Inside our JavaScript, we will use the fetch function to get a json response which we can use to gather the data we need .

Note : In the url of the fetch function below  replace <mark>YOUR_API_KEY</mark> with out your actual key 

The following code has a simple fetch function with the GET request to the REST API i.e. IP Geolocation API
 
```js

fetch("https://api.geoapify.com/v1/ipinfo?&apiKey=YOUR_API_KEY", requestOptions)
  .then(
    (response) =>
      response.json()
  )
  .then((data) => {
    console.log(data)
  })
  .catch(err => console.log(err))

var requestOptions = {
  method: 'GET',
};
```
Note that just for now we are just console logging the entire .json data in the console , but later we will actually use the data and put it on a map .
So if you check the console you should see that the API with an object with lot many properties.

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b9fwma99kdvwxphskx68.png" alt="console" >
  <figcaption>console</figcaption>
</figure>

If you want to view the return JSON data clearly , install any <mark>JSON</mark> formatter browser extension  open this link in the web browser and you would clearly be able to see every data piece nicely formatted in a readable way .
`https://api.geoapify.com/v1/ipinfo?&apiKey=YOUR_API_KEY` 

The API shows my current location with all the other details as you can see some of which I have blurred.

Now after we have got this data , we need to put this on a map and we will use OpenLayers to make our job easier 
If you see the quick start guide [here](https://openlayers.org/en/latest/doc/quickstart.html). They have shown us a working example with a HTML file . We need to include this JS library using CDN like so :
```html
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.14.1/build/ol.js"></script>
<link rel="stylesheet"href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.14.1/css/ol.css" type="text/css">
```
We have include the JS library and it's stylesheet files as well.

Now inside our JavaScript file ,  we can create a new map like so:
This is exactly what is mentioned in the Quick start guide 
```js
var map = new ol.Map({

    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    view: new ol.View({
      center: ol.proj.fromLonLat([37.41, 8.82]),
      zoom: 4
    })
  });
```
Note that the latitude and longitude for the location on this map is <mark>harcoded</mark> as  (37.41, 8.82)  which is not what we want .

Let's put this piece of code above in a function and call it `coordinates()`

Now back to our fetch function instead of console logging our entire data , lets pass all this data to the coordinates function so that it can be mapped .

```js

fetch("https://api.geoapify.com/v1/ipinfo?&apiKey=18e9b1ba1eaf4731b0347ede6565a8a9", requestOptions)
  .then(
    (response) =>
      response.json()
  )
  .then((data) => {
  
    coordinates(data) // passing in the data 

  })
  .catch(err => console.log(err))

var requestOptions = {
  method: 'GET',
};
```
```js
function coordinates(data) { // data is passed as a parameter 
  var map = new ol.Map({

    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    view: new ol.View({
      center: ol.proj.fromLonLat([37.41, 8.82]),
      zoom: 12
    })
  });
}
```
Now to replace the hardcoded lat , long values with the latitude and longitude values returned by the Geoapify API after it detects the user location .

<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b9fwma99kdvwxphskx68.png" alt="console" >
  <figcaption>Note the latitude and longitude values</figcaption>
</figure>

In the above image as you can see the API returned lots of data that we can use , but if you notice carefully it also returns the <mark>latitude and longitude values inside the location property of the object</mark>. 

To access it we can type : <mark>data.location.longitude</mark> to get the user's longitude .

So now in our coordinates function we can replace the hardcoded values with :

```js
function coordinates(data) {
  var map = new ol.Map({

    target: 'map', // div map is targeted in html
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    view: new ol.View({
      center: ol.proj.fromLonLat([data.location.longitude, data.location.latitude]), // hard coded values replaced 
      zoom: 12 // how zoomed in the map is 
// the user can also change the zoom level of the map with the inbuilt buttons in the map by OpenLayers
    })
  });
}
```

Now as you can see our <mark>map is displayed in a div tag with id or class  'map' </mark> so you can create it like so :
```html
<div id="map" class="map"></div>
```

Now add some basic CSS to the map div using external stylesheets file

```CSS
.map {
  height: 650px;
  width: 100%;
}
```

And now whenever any user opens up your website , it will show the user's approximate location through this map . 

I went ahead and added the other details like I.P. and country name in the form of text on the page.


<figure>
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5odmt3a1n77030aiw9iv.png" alt="result" >
  <figcaption>final result</figcaption>
</figure>

Live Demo : [here](https://satvik.ninja/your-location)