In today’s digital world, location-based features are everywhere — from ride-hailing apps to food delivery, maps, and weather apps. At the heart of these features are latitude and longitude coordinates, which pinpoint any location on Earth.
In this blog post, you’ll learn:
- What latitude and longitude are
- How to get a user’s location using the browser
- How to use it in a web app (e.g., display on a map, send to a backend, or get directions)
Latitude and Longitude are coordinates used to specify any location on Earth:
- Latitude: Measures how far north or south of the equator a place is (from -90 to +90).
- Longitude: Measures how far east or west of the Prime Meridian a place is (from -180 to +180).
For example, the coordinates for Lagos, Nigeria are approximately:
makefileCopyEdit
Latitude: 6.5244
Longitude: 3.3792
📦 Getting User Location with JavaScript
You can get the user’s current location using the Geolocation API, built into modern browsers.
✅ Step 1: Basic JavaScript CodehtmlCopyEdit
<script>
navigator.geolocation.getCurrentPosition(
function(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
console.log("Latitude:", latitude);
console.log("Longitude:", longitude);
},
function(error) {
console.error("Error getting location:", error);
}
);
</script>
⚠️ Users must grant permission for location access. Always handle errors and permissions properly.🗺️ Displaying Location on a Map with Leaflet.js
Leaflet is a powerful open-source JavaScript library for interactive maps.
✅ Step 2: Include LeaflethtmlCopyEdit
<link
rel="stylesheet"
href="https://unpkg.com/[email protected]/dist/leaflet.css"
/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
✅ Step 3: Add Map Containerhtml
CopyEdit
<div id="map" style="height: 400px;"></div>
✅ Step 4: Display Map and Markerhtml
CopyEdit
<script>
navigator.geolocation.getCurrentPosition(function (position) {
const lat = position.coords.latitude;
const lng = position.coords.longitude;
const map = L.map("map").setView([lat, lng], 13);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: "Map data © OpenStreetMap contributors"
}).addTo(map);
L.marker([lat, lng])
.addTo(map)
.bindPopup("You are here!")
.openPopup();
});
</script>
🛰️ Sending Coordinates to the Backend (e.g., PHP)
You can send latitude and longitude to your server using AJAX.
✅ Step 5: Send to PHP using FetchhtmlCopyEdit
<script>
navigator.geolocation.getCurrentPosition(function (position) {
const data = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
fetch("save_location.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
});
</script>
✅ Step 6: PHP to Receive Itphp
CopyEdit
<?php
$data = json_decode(file_get_contents("php://input"), true);
$lat = $data['lat'];
$lng = $data['lng'];
// Save to database or use it
echo "Received location: $lat, $lng";
?>
📦 Real-World Use Cases
- Ride-hailing: Find nearby drivers or riders
- Delivery: Get real-time driver location
- Weather apps: Show local weather based on current coordinates
- Check-in apps: Verify user's presence at a physical location
- Store locator: Help users find nearest branch/outlet
- Always ask for permission before using location
- Handle error cases (user blocks location, no GPS, etc.)
- Never expose sensitive location data without user consent
- If precision is not needed, round the coordinates to 3–4 decimal places
Latitude and longitude open a world of possibilities in web applications. Whether you’re tracking movement, showing a live map, or personalizing experiences based on location, understanding how to work with geographic coordinates is an essential web development skill.
Now that you’ve seen how to get and use coordinates on the front-end and back-end, try integrating location features into your own project!