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 OpenLayers and Geoapify to display a map with the city of the user in focus .
OpenLayers 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 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 IP Geolocation API 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 ,
- Go to the Dashboard
- Create a new project and name it whatever you want
- On the left side bar , go to the API keys section
- Choose the type of App as IP Geolocation API as this is the API we will be using
- 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 YOUR_API_KEY 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
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.
If you want to view the return JSON data clearly , install any JSON 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. They have shown us a working example with a HTML file . We need to include this JS library using CDN like so :
<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
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 harcoded 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 .
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',
};
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 .
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 latitude and longitude values inside the location property of the object.
To access it we can type : data.location.longitude to get the user's longitude .
So now in our coordinates function we can replace the hardcoded values with :
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 map is displayed in a div tag with id or class 'map' so you can create it like so :
<div id="map" class="map"></div>
Now add some basic CSS to the map div using external stylesheets file
.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.
Live Demo : here
Top comments (0)