🚀 What You'll Learn
In this quickstart guide, you'll learn how to: • Get user's location in 3 simple steps • Show latitude and longitude coordinates • Convert coordinates to a readable address • Handle errors when location access is denied
No prior experience needed! Just basic HTML and JavaScript knowledge. 😊
Think of it as your website asking: "Where are you right now?"
The browser can find your location using GPS (on mobile) or your internet connection. But don't worry - it always asks for permission first! 🔒
📱 Step 1: Check if Location is Available
Before we ask for location, let's check if the browser supports it:
1
2
3
4
5
6
// Step 1: Check if location is supported
if (navigator.geolocation) {
console.log("✅ Location is supported!");
} else {
console.log("❌ Location is not supported");
}📍 Step 2: Ask for User's Location
Now let's ask the user for their location. The browser will show a permission popup:
1
2
3
4
5
6
7
8
9
10
11
12
13
// Step 2: Ask for location
navigator.geolocation.getCurrentPosition(
function(position) {
// Success! We got the location
console.log("Got location!");
console.log("Latitude:", position.coords.latitude);
console.log("Longitude:", position.coords.longitude);
},
function(error) {
// Oops! Something went wrong
console.log("Error:", error.message);
}
);🎯 Step 3: Create a Simple HTML Page
Let's put it all together in a simple HTML page you can try:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<!DOCTYPE html>
<html>
<head>
<title>My Location App</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background-color: #f0f8ff;
}
.container {
background: white;
padding: 30px;
border-radius: 10px;
text-align: center;
}
button {
background-color: #4CAF50;
color: white;
padding: 15px 30px;
font-size: 18px;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
#result {
margin-top: 20px;
padding: 15px;
background-color: #e8f5e8;
border-radius: 5px;
border-left: 4px solid #4CAF50;
}
</style>
</head>
<body>
<div class="container">
<h1>🌍 Find My Location</h1>
<p>Click the button to get your current location!</p>
<button onclick="getMyLocation()">📍 Get My Location</button>
<div id="result"></div>
</div>
<script>
function getMyLocation() {
const resultDiv = document.getElementById('result');
// Check if location is supported
if (!navigator.geolocation) {
resultDiv.innerHTML = '❌ Sorry, location is not supported by your browser';
return;
}
// Show loading message
resultDiv.innerHTML = '🔍 Finding your location...';
// Ask for location
navigator.geolocation.getCurrentPosition(
function(position) {
// Success! Show the location
const lat = position.coords.latitude;
const lon = position.coords.longitude;
resultDiv.innerHTML = `
<h3>✅ Found your location!</h3>
<p><strong>Latitude:</strong> ${lat}</p>
<p><strong>Longitude:</strong> ${lon}</p>
<p><small>These are your coordinates on Earth! 🌍</small></p>
`;
},
function(error) {
// Handle different types of errors
let message = '';
if (error.code === 1) {
message = 'You denied location access. Please allow location to continue.';
} else if (error.code === 2) {
message = 'Location information is unavailable.';
} else {
message = 'Timeout - it took too long to get your location.';
}
resultDiv.innerHTML = '❌ ' + message;
}
);
}
</script>
</body>
</html>🎉 Try It Yourself!
Copy the code above, save it as location.html, and open it in your browser. Click the button and allow location access - you'll see your coordinates! 🎯
🏠 Step 4: Convert Coordinates to Address (Bonus)
Coordinates are cool, but what if you want to show the actual address? Let's add that magic! ✨
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Function to convert coordinates to address
async function getAddress(latitude, longitude) {
try {
// Use a free API to get address
const response = await fetch(
`https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}`
);
const data = await response.json();
return data.display_name; // This is the full address
} catch (error) {
return 'Could not get address';
}
}🔥 Complete Example with Address
Here's the improved version that shows both coordinates AND address:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Updated function that shows coordinates AND address
async function getMyLocationWithAddress() {
const resultDiv = document.getElementById('result');
if (!navigator.geolocation) {
resultDiv.innerHTML = '❌ Location not supported';
return;
}
resultDiv.innerHTML = '🔍 Finding your location...';
navigator.geolocation.getCurrentPosition(
async function(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
// Show coordinates first
resultDiv.innerHTML = `
<h3>✅ Found your location!</h3>
<p><strong>Latitude:</strong> ${lat}</p>
<p><strong>Longitude:</strong> ${lon}</p>
<p>🌐 Getting your address...</p>
`;
// Get address
const address = await getAddress(lat, lon);
// Show everything
resultDiv.innerHTML = `
<h3>✅ Found your location!</h3>
<p><strong>Latitude:</strong> ${lat}</p>
<p><strong>Longitude:</strong> ${lon}</p>
<p><strong>Address:</strong> ${address}</p>
<p><small>Pretty cool, right? 🎯</small></p>
`;
},
function(error) {
resultDiv.innerHTML = '❌ Error getting location: ' + error.message;
}
);
}
// Helper function to get address from coordinates
async function getAddress(latitude, longitude) {
try {
const response = await fetch(
`https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}`
);
const data = await response.json();
return data.display_name;
} catch (error) {
return 'Could not get address';
}
}💡 What Just Happened?
- Browser asks for permission - User clicks "Allow" or "Block"
- If allowed - Browser finds your location using GPS/WiFi/IP
- Returns coordinates - Latitude and Longitude numbers
- API converts coordinates - Free service turns numbers into readable address
- Display everything - Show both coordinates and address to user
🚨 Common Issues & Solutions
Problem: "User denied location access" Solution: Explain why you need location before asking
Problem: "Location unavailable" Solution: User might be indoors or have poor GPS signal
Problem: "Timeout" Solution: Increase timeout or try again
🎯 Quick Tips for Success
✅ Always ask permission nicely - Explain why you need location ✅ Test on your phone - Location works best on mobile devices ✅ Use HTTPS - Location API only works on secure websites ✅ Handle errors - Always show helpful messages when things go wrong ✅ Be patient - Getting location can take a few seconds
🔥 Real-World Examples
Food Delivery Apps - "Find restaurants near you" Weather Apps - "Weather for your current location" Maps - "You are here" marker Emergency Services - Share location for help Social Media - "Check in at this location"
🎉 Congratulations!
You've learned how to get user location in just a few simple steps! 🚀
You can now: • Ask for user's location • Show coordinates • Convert coordinates to readable addresses • Handle errors gracefully
Start building your location-aware web app today! 💪
🔗 Next Steps
Want to learn more? • MDN Location API Docs - Official documentation • OpenStreetMap API - Free address lookup service • Try building a "Find Coffee Shops Near Me" app! • Add a map to show the location visually

