$(document).ready(function(){
$("#getLocation").on("click", function(){
$.getJSON('https://geoip-db.com/json/geoip.php?jsonp=?')
.done (function(location) {
$('#city').html(location.city);
});
});
});
This is the current JavaScript I've been using, and here is the link to the CodePen I'm using it for. I'm using the location of the users city to find the weather of that city as well.
I've read on multiple sites about how to use several different API's to get the users city location, but non have worked in my project. Thanks for the help, in advance.
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:
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: