Accessing location using Javascript - javascript

I run the code shown below from different places but this results in same latitude and longitude value at different places.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body onload="getLocation()">
<p id="demo"> </p>
<script>
var x= document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML= position.coords.latitude;
x.innerHTML= position.coords.longitude;
var lat=position.coords.latitude;
var lon=position.coords.longitude;
}
</script>
**strong text**</body>
</html>
Any help would be appreciated.

In short, the problem isn't with your code, but most likely with your device. I can tell you're using the demo code from the W3Schools article on the geolocation API. That code seems to work fine for me, at least as much as I would expect.
Geolocation isn't terribly precise in all cases. According to MDN, the method use to determine location will be the most accurate available for your device at that time. If you're testing on a desktop browser, the results might be no more accurate than to the nearest city, and in some cases even more inaccurate than that (My home in Michigan registers as the middle of New York state, for some weird reason). If you test on a 3g or 4g phone, you might get better results, down to the nearest broadcast area. If you test on a phone with GPS, you might get highly accurate data, where you'll notice a difference if you move even a few feet or so. I say 'might' for these cases, because location data is a huge privacy concern area, and there's a lot of things that might interfere with geolocation to protect a user's privacy.
If you're seeing the same result from relativly small moves, this would easily be the cause. If you've travelled a few hundred miles to run your code elsewhere, then I would have to admit that there's something

Related

Why is JavaScript geolocation only Approximate?

No matter how I use the JavaScript:
position.coords.latitude;
position.coords.longitude;
The returned coordinates are always at least a few city blocks off.
So - it will show the "start point" or "Your location" as a few streets over?
This approximate result seems new, as the code I used before produced a more accurate result.
I have tested on all browser's from a "https" web page.
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + '/' + position.coords.longitude;
}
</script>
Has something changed?
Why is the produced coordinates only approximate?
This is a tradeoff between speed and accuracy. Gelocation.getCurrentPosition() at MDN details the optional parameter enableHighAccuracy
JavaScript geolocation is only an approximation of the device's actual location because it relies on the device's built-in GPS, Wi-Fi, IP address lookup and/or network triangulation to determine your location. Additionally, the Geolocation API provides an estimated location, not an exact location. The accuracy of the location information can vary greatly and can be influenced by various factors, including the type of device, its settings, and the environment (buildings, trees, etc) in which it is used.
I used your function and indeed the latitude and longitude coordinates were not exact, there is a difference of a few meters (more than 30-40).

html geolocation: Unknown error acquiring position

I am trying to use HTML geolocation to get my position. Funny thing is, it was working brilliantly until some seemingly random point in the day when it just stopped working. Now all I get is the error callback with a message:
Unknown error acquiring position
This happened on the day I first started to develop the app. It is a web app built in Node/Express. The browser I am using is Firefox v53 64-bit.
Location is allowed, and I have also tried a fix that I found online which involves going to about:config and changing geo.wifi.uri from:
https://www.googleapis.com/geolocation/v1/geolocate?key=%GOOGLE_API_KEY%
to
https://www.googleapis.com/geolocation/v1/geolocate?key=test
This did not work for me.
This does however work on my phones Firefox app, but not the Google Chrome app.
Heres an example code snippet:
const geo = navigator.geolocation;
geo.getCurrentPosition(success, failure);
function success(position) {
lat = position.coords.latitude;
lng = position.coords.longitude;
$('#coords').val(lat + ',' + lng);
mapView.setCenter(ol.proj.fromLonLat([lng, lat]));
}
function failure(error) {
console.log(error.message);
}
The full page: https://github.com/ThriceGood/Spots/blob/master/views/index.html
Can anyone shed some light on this issue?
What worked for me was changing geo.wifi.uri to:
https://location.services.mozilla.com/v1/geolocate?key=test
As per this page: navigator.geolocation.getCurrentPosition do not work in Firefox 30.0

I want to get my accurate latitude longitude of my linux device on command line. Like Geolocation in HTML5. I dont have access to browser

I want to send email of current Lat Long from my Linux device. I tried geo location in HTML5 browsers, it works great. But i want it on command line. I tried so many options such as curl, geoip to some websites by IP, but they all show my ISP's position, not mine.
I prefer using it on command line or python etc tools.
I could successfully write a python program which opens a locally saved page of HTML5 geolocation code and shows accurate lat long also. Then automatically python fetches lat long from browser and shows on terminal.
File: test.py
from splinter.browser import Browser
import os.path
import time
browser = Browser()
browser.visit('file://' + os.path.realpath('geo.html'))
time.sleep(5)
elements = browser.find_by_css("#demo")
div = elements[0]
print div.value
browser.quit()
File: geo.html
<html>
<head>
<title>Test</title>
<p id="demo"></p>
<script type="text/javascript">
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</head>
<body>
<p>The element below will receive content</p>
<div id="div" />
<script type="text/javascript">getLocation()</script>
</body>
</html>
But a bug is there, that every time python opens the browser, i have to click "Share location: Yes" in browser. Because the page is running on local server, not on any webserver. So this solution was not applicable.
Can anyone suggest me reliable solution to get my current lat long in linux in command line?
On Linux you need to talk to gpsd.
You could talk to libgps: http://manpages.ubuntu.com/manpages/wily/en/man3/libgps.3.html
You could use the DBUS interface.
Or you could use the python interface: how to use/install gps python library

How can I get user's location without asking for the permission or if user permitted once so need not to ask ever again?

I am creating a portal using MySQL, JavaScript and Ajax and I want to fetch user's location in terms of latitude and longitude. if it is not possible to fetch the location without asking then once user grant the permission, I could fetch the location from any page without asking ever again.
Thanks in Advance.
3 ways to do this in this answer:
Get a GPS precise location asking the user to allow access to its browser's API
Get an approximate location (country, city, area) using an external GeoIP service
Get an approximate location (country, city, area) using CDN service
Ask the user to allow access to its browser's API
You can get the location of the client using HTML5 features. This will get you the exact location of the user if it is done from a device which has a GPS, or an approximate location. Once the user approved to share his location, you'll get it without any more approval.
This solution uses Geolocation.getCurrentPosition(). It is required for most cases to do this under HTTPS protocol.
If you are in a hurry, here is a CodePen with this solution: https://codepen.io/sebastienfi/pen/pqNxEa
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Try It</button>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
// Success function
showPosition,
// Error function
null,
// Options. See MDN for details.
{
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
});
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
Handling Errors and Rejections
The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
Displaying the Result in a Map
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?center=
"+latlon+"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
GeoIP
If the solution above doesn't work in your scenario, you can obtain an approximate position using IP's location. You will not necessarily get the exact location of the user, but may end up with the location of the nearest Internet node in the user's connection point area, which may be close enough for 99% of the use cases (country, city, area).
As this is not precise but doesn't require the user's approval, this may also meet your requirements.
Find below 2 ways to do that. I would recommend doing this using the CDN solution because it is faster and yes, speed matters a lot.
Get an approximate location (country, city, area) using an external GeoIP service
Many external services allows you to obtain the GeoIP location.
Here is an example with Google.
To get your Google API Key, go here: https://developers.google.com/loader/signup?csw=1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Get web visitor's location</title>
<meta name="robots" value="none" />
</head>
<body>
<div id="yourinfo"></div>
<script type="text/javascript" src="http://www.google.com/jsapi?key=<YOUR_GOOGLE_API_KEY>"></script>
<script type="text/javascript">
if(google.loader.ClientLocation)
{
visitor_lat = google.loader.ClientLocation.latitude;
visitor_lon = google.loader.ClientLocation.longitude;
visitor_city = google.loader.ClientLocation.address.city;
visitor_region = google.loader.ClientLocation.address.region;
visitor_country = google.loader.ClientLocation.address.country;
visitor_countrycode = google.loader.ClientLocation.address.country_code;
document.getElementById('yourinfo').innerHTML = '<p>Lat/Lon: ' + visitor_lat + ' / ' + visitor_lon + '</p><p>Location: ' + visitor_city + ', ' + visitor_region + ', ' + visitor_country + ' (' + visitor_countrycode + ')</p>';
}
else
{
document.getElementById('yourinfo').innerHTML = '<p>Whoops!</p>';
}
</script>
</body>
</html>
Get an approximate location (country, city, area) using CDN service
An alternative to using external services is provided by most of the CDN. The advantage of this solution is that no extra HTTP request is required, so it is faster. If you already have a CDN, this is the way to go. You can use CloudFlare, CloudFront, etc.
In this scenario, you will most likely end up with the location as a parameter of the HTTP request's header, or even directly in the window object so you can get it with Javascript. Read the CDN's documentation to know more.
Edited on mid December 2018 to add more options.
You can go for an external service like https://www.geolocation-db.com. They provide a geolocation service based on IP addresses where you don't need user permission.
JSON: https://geolocation-db.com/json/
JSONP: https://geolocation-db.com/jsonp/
Try this example:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Geo City Locator</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div>Country: <span id="country"></span></div>
<div>State: <span id="state"></span></div>
<div>City: <span id="city"></span></div>
<div>Latitude: <span id="latitude"></span></div>
<div>Longitude: <span id="longitude"></span></div>
<div>IP: <span id="ip"></span></div>
<script>
$.getJSON('https://geolocation-db.com/json/')
.done (function(location) {
$('#country').html(location.country_name);
$('#state').html(location.state);
$('#city').html(location.city);
$('#latitude').html(location.latitude);
$('#longitude').html(location.longitude);
$('#ip').html(location.IPv4);
});
</script>
</body>
</html>
Call below API to fetch location details using ip address
http://ip-api.com/json/
Limit: 45 requests per minute from an IP address
Documentation : https://ip-api.com/docs/api:json
It's possible to guess latitude and longitude based on the origin IP address of a web request. You need access to a database or service which maps IPs to locations, such as MaxMind's geoip (https://www.maxmind.com/en/geoip-demo). There should be JavaScript / PHP wrappers available for services such as these which you can make use of.
GeoIP lookup is not very reliable and can get out of date easily. If you need something more accurate you'll have to solicit some information from the user, such as a zip code.

Java script logic error

I am new to Java scripting and need quick help. Here is my code:
<html>
<head>
<title> GeoLocation Application </title>
<script>
$counter=0;
while ($counter < 10) {
if (!navigator.geolocation) {
alert('Your browser does not support geolocation');
} else {
navigator.geolocation.getCurrentPosition(success, error);
document.write("Count ",$counter,"<br>");
}
$counter ++;
}
function success(position) {
lat = position.coords.latitude;
lng = position.coords.longitude;
alert (lat +','+lng);
document.write("calling update mysql");
//document.location='update_java_data.php?lat=' + lat+'&lng='+lng;
}
function error(error) {
alert('an erro occured, error code is '+error);
}
</script>
</head>
<body>
<h1> Hello </h1>
</body>
</html>
I am trying to get coordinates using navigator 10 times. But when I am seeing only a quick list of counter display from 0 to 9, but only once it displays ""calling update mysql".
To me it means it only executed success function once.
Any idea how I can make it get the coordinate 10 times (means it should also call success function 10 times I guess)?
I would suggest instead looking at using the setInterval function to do your lat/long collection at specified intervals... If what you have above runs successfully, it would probably collect the same point 10 times quickly.
So, since you do those function calls without any type of a wait/interval, they all fire off at basically the same time (0-9 counter display)... As for only seeing the 'calling update mysql' once, I would imagine that it has something to do with you changing the location of the window to a different url, and the other calls not being able to reach the success function since you have already mo

Categories