To elaborate on my previous answer, a cleaner and more vanilla JavaScript way to get the coordinates is like so.
This is just a few short lines longer and the benefits are massive:
- Don't have to include jQuery library, which is massive and slows down page load times
- This means you won't have to rely on a HEAVY EXTERNAL API to make AJAX calls for the same data (and other useless API-specific info e.g. requestID) and will seriously streamline your application.
- Avoids the use of many callbacks and thus avoids callback hell.
See image below for results. Super lightweight and fast. For more detailed information, have a look at MDN - Using Geolocation.
if ("geolocation" in navigator) {
// Do something with coordinates returned
function processCoords(position) {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
let first_div = document.querySelector('div');
let el_h2 = document.createElement('h2');
// Set h2 text as coordinates
el_h2.innerText = `Latitude: ${latitude}, Longitude: ${longitude}`;
// Append h2 to document
first_div.appendChild(el_h2);
}
// Fetch Coordinates
navigator.geolocation.getCurrentPosition(processCoords);
}
To get the City:
It's usually best practice to store the coordinates only in your db
and then make separate city requests when required. This makes things
easier when you want to implement say a Map View on Mobile or Desktop,
which all use coordinates rather than names for plots.
You can use the Google Maps API and passing in the LatLong data directly. Someone has created a gist on how to do it here.
Benefit of using GMaps instead of Geo-IP:
- Google Maps API is heavily, heavily, heavily optimised. From faster
servers to better-written code. You can also import a specific part
of the GMaps API so you can cut down on your source code size. All
of this adds up to a much faster experience.
- GMaps can be assumed to be around for longer than a 3rd party site like Geo-Ip.
