Creating personalized apps based on location data is a rewarding challenge for developers. In this tutorial, we'll use the ipstack API to build an app that shares top nearby deals based on user location. By the end of this guide, you'll have a functioning backend with a simple frontend to showcase location-specific deals.
Overview
The goal:
Fetch user location using the ipstack API.
Match user location with nearby deals stored in a database or API.
Display those deals using a user-friendly UI.
What You’ll Need
An ipstack API key.
A backend framework (e.g., Node.js).
Sample data for deals or a deals API (e.g., mock data in JSON).
Optional: A frontend library like React or plain HTML/JavaScript.
To make the tutorial interactive, you can follow along with the ipstack API documentation.
Step 1: Fetch Location Data
Start by integrating the ipstack API to retrieve geolocation data.
Code Example
Here’s how to fetch user location data based on an IP address:
const axios = require('axios');
const getLocation = async (ipAddress) => {
const API_KEY = 'your_ipstack_api_key';
const url = `http://api.ipstack.com/${ipAddress}?access_key=${API_KEY}`;
try {
const response = await axios.get(url);
const data = response.data;
console.log('User Location:', data);
return {
city: data.city,
region: data.region_name,
country: data.country_name,
latitude: data.latitude,
longitude: data.longitude,
};
} catch (error) {
console.error('Error fetching location:', error.message);
}
};
// Example usage:
getLocation('172.70.143.208');
Sample Response
{
"ip": "172.70.143.208",
"city": "Singapore",
"region_name": "Central Singapore",
"country_name": "Singapore",
"latitude": 1.287950038909912,
"longitude": 103.8517837524414
}
Step 2: Create a Mock Deals Database
To keep things simple, let’s use a JSON file to store some sample deals.
deals.json
[
{
"id": 1,
"title": "20% off Electronics",
"city": "Singapore",
"latitude": 1.290270,
"longitude": 103.851959
},
{
"id": 2,
"title": "Buy 1 Get 1 Free - Coffee",
"city": "Singapore",
"latitude": 1.300270,
"longitude": 103.860959
}
]
Step 3: Match Deals to User Location
We’ll filter deals based on user location using a simple distance formula.
Haversine Formula
This formula calculates the distance between two geographic coordinates.
const getDistance = (lat1, lon1, lat2, lon2) => {
const toRad = (value) => (value * Math.PI) / 180;
const R = 6371; // Radius of Earth in km
const dLat = toRad(lat2 - lat1);
const dLon = toRad(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRad(lat1)) *
Math.cos(toRad(lat2)) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c; // Distance in km
};
Filter Nearby Deals
Here’s how to find deals within a specific radius:
const filterDeals = (userLat, userLon, deals, radius = 10) => {
return deals.filter((deal) => {
const distance = getDistance(userLat, userLon, deal.latitude, deal.longitude);
return distance <= radius;
});
};
// Example usage:
const userLat = 1.287950038909912;
const userLon = 103.8517837524414;
const deals = require('./deals.json');
const nearbyDeals = filterDeals(userLat, userLon, deals, 5);
console.log('Nearby Deals:', nearbyDeals);
Step 4: Display Deals in the Frontend
You can keep the frontend lightweight or build something dynamic. Here’s an example using plain HTML and JavaScript.
HTML Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Nearby Deals</title>
</head>
<body>
<h1>Top Deals Near You</h1>
<ul id="deals-list"></ul>
<script>
const deals = [
{ title: "20% off Electronics", city: "Singapore" },
{ title: "Buy 1 Get 1 Free - Coffee", city: "Singapore" }
];
const list = document.getElementById('deals-list');
deals.forEach(deal => {
const li = document.createElement('li');
li.textContent = `${deal.title} - ${deal.city}`;
list.appendChild(li);
});
</script>
</body>
</html>
Step 5: Connect Backend and Frontend
Create an endpoint to serve the filtered deals and fetch them dynamically in the frontend.
Express.js Example
const express = require('express');
const app = express();
const deals = require('./deals.json');
app.get('/api/deals', (req, res) => {
const userLat = parseFloat(req.query.lat);
const userLon = parseFloat(req.query.lon);
const radius = parseInt(req.query.radius) || 10;
const nearbyDeals = filterDeals(userLat, userLon, deals, radius);
res.json(nearbyDeals);
});
app.listen(3000, () => console.log('Server running on port 3000'));
Helpful Resources
Here are a few links to deepen your understanding:
ipstack API Documentation: Comprehensive guide to ipstack API features.
Haversine Formula Explained: Learn the math behind distance calculation.
Node.js Official Guide: Explore Node.js essentials.
Top comments (1)
Just a heads up that you can add highlighting to the code blocks if you'd like. Just change:
... to specify the language:
More details in our editor guide!