I needed to fetch a visitor's coordinates, then pass them into a form, which then displayed local businesses in their area. The first part was just getting their latitude and longitude.
How do you find a visitor's latitude and longitude using jQuery?
- Get the visitor's permission to access their location
- Use the JavaScript Geolocation API to get the GPS position from the visitor's device, or fallback to the location of their IP address
- Display the latitude and longitude in the browser window
It's important that when you run this on a server, you use it on https, not http. If you don't, Chrome won't let the request proceed. It doesn't seem to have the same problems if you're doing it on your desktop.
Here is the entire code I used to do this in testing. You can save it as a .html file and run it on your computer or server, if you'd like.
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.wrapper {
margin-top:50px;width:100%;text-align:center;
}
#bigbutton {
border:1px solid #000;font-size:25px;padding:10px 20px;
}
</style>
</head>
<body>
<div class="wrapper">
<button id="bigbutton">Where Am I?</button>
<p id="demo"></p>
</div>
<script>
jQuery(document).ready(function($) {
$("#bigbutton").click(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoSucc, geoErr, geoOpt);
} else {
$("#demo").html('Geolocation is not supported by this browser.');
}
});
function geoSucc(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$("#demo").html(latitude + ',' + longitude);
}
function geoErr(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
$("#demo").html('User denied the request for Geolocation.');
break;
case error.POSITION_UNAVAILABLE:
$("#demo").html('Location information is unavailable.');
break;
case error.TIMEOUT:
$("#demo").html('The request to get user location timed out.');
break;
case error.UNKNOWN_ERROR:
$("#demo").html('An unknown error occurred.');
break;
}
}
var geoOpt = {
timeout: 3000,
maximumAge: 30
}
});
</script>
</body>
Let's break the code down...
Get the visitor's permission to access their location
Every time this runs, it will create a popup asking the visitor if they are happy to share their location. Sometimes the response is cached.
Occasionally, the request gets stuck. That's why I've set the timeout to 3000 milliseconds in geoOpt. It was all fine on my desktop, but not on my phone. The maximumAge parameter is for the same reason.
Use the JavaScript Geolocation API to get the coordinates
HTML5 gave us a pretty handy Geolocation function. The key part of the code that runs it is:
navigator.geolocation.getCurrentPosition(geoSucc, geoErr, geoOpt);
You don't even need the geoErr or geoOpt if you don't need the extra options.
Note that the parameters must match the functions or variables of the same name. You can name them anything you like, just keep it consistent and understandable.
Inside the geoSucc function, notice that you call the latitude and longitude with position.coords.latitude and position.coords.longitude respectively.
The geoErr function is just basic error checking. There's nothing special about it. You don't have to return the response to the html. You could just as easily print it to console.log.
Display the latitude and longitude in the browser window
We then display the coordinates to the visitor inside the geoSucc function with the line:
$("#demo").html(latitude + ',' + longitude);
This uses jQuery to replace anything inside the <p id="demo"> with the latitude and longitude that was just pulled.
If you wanted to update a form, you'd do it with this line.
Note that I only broke the coordinates into the variables latitude and longitude for ease of reading. If you're only going to use them once, just skip the variable creation.
How to display a map of the visitor's location
With the code you already have in place, it's simple to add a map of the visitor's location. You'll need a Maps API key from Google.
Add this to the bottom of the geoSucc function:
$("#map").html('<img src="https://maps.google.com/maps/api/staticmap?key=YOURAPIKEY¢er=' + latitude + ',' + longitude + '&zoom=14&size=400x300&sensor=false&markers=' + latitude + ',' + longitude + '" />');
Replace YOURAPIKEY with the key you got from Google.
That will give you a result like this:
How to get a visitor's latitude and longitude with JavaScript
Let's say you didn't want to use jQuery. If you want to get a user's coordinates with JavaScript, the process is the same and the code is very similar.
This code does away with the button and displays on page load:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.wrapper {
margin-top:50px;width:100%;text-align:center;
}
</style>
</head>
<body>
<div class="wrapper">
<p id="demo"></p>
<p id="map"></p>
</div>
<script>
var d = document.getElementById('demo');
var m = document.getElementById('map');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoSucc, geoErr, geoOpt);
} else {
d.innerHTML = 'Geolocation is not supported by this browser.';
}
function geoSucc(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
d.innerHTML = latitude + ',' + longitude;
m.innerHTML = '<img src="https://maps.google.com/maps/api/staticmap?key=AIzaSyDDF6tyjlqvwNoWDx31B0zSvkOI-RaJ-08¢er=' + latitude + ',' + longitude + '&zoom=14&size=400x300&sensor=false&markers=' + latitude + ',' + longitude + '" />';
}
function geoErr(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
d.innerHTML = 'User denied the request for Geolocation.';
break;
case error.POSITION_UNAVAILABLE:
d.innerHTML = 'Location information is unavailable.';
break;
case error.TIMEOUT:
d.innerHTML = 'The request to get user location timed out.';
break;
case error.UNKNOWN_ERROR:
d.innerHTML = 'An unknown error occurred.';
break;
}
}
var geoOpt = {
timeout: 3000,
maximumAge: 30
}
</script>
</body>
Why not use PHP to get the visitor's location?
PHP is a server side language. That means the only way you can get the visitor's IP address is if the browser happens to pass it through as a $_SERVER variable. Browsers are notoriously inconsistent in this, so you really can't rely on it.
Another downside to using PHP is that you don't get access to the GPS if the visitor is on a mobile device. This greatly enhances the accuracy.
With my particular Internet Service Provider, my desktop browser often thinks I'm in Brisbane or Sydney, rather than in Perth, which is where I actually am. That's off by several thousand km. Without even using a VPN!
The other reason is that it's polite (and I think required if you're in the EU) to ask permission before you pull a visitor's actual location.
Even if you're not storing the location, done improperly or without their knowledge, it can come across as creepy, which is bad for business.