HTML/Javascript: access to geolocation from local HTML file - javascript

I'm trying to implement a web page which displays your location on a map. Given that the person accessing the web page may not have internet access, I want the web page to be a local HTML file.
These days, for security reasons, it doesn't seem to be possible to access geolocation form a local HTML file.
Any ideas as to how I can get access to geolocation from a local HTML file?
Thanks
I have tried accessing my local HTML file via a local web server but these only allow http pages whereas geolocation seems to be dependent upon an https file.

To use Geolocation API your application should run on HTTPS protocol or on the localhost web server. Otherwise, Geolocation API will not work.
Most of all you will get the coordinates of your internet provider stations :)
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(position) {
console.log("Latitude: " + position.coords.latitude +
" Longitude: " + position.coords.longitude);
}

<button onclick="getLocation()">Get Location</button>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
alert("Latitude: " + position.coords.latitude +
"\nLongitude: " + position.coords.longitude);
}
</script>

Related

Redirection to different landing page according to city - Wordpress Site

I am new to Website development so I want to redirect people from specific cities to the specific landing page and all the rest to normal homepage in a WordPress site. I have to do this for a client. is there a sample blog or code that can help me I got the longitude and latitude via script I want to detect the location automatically and then redirect according to the city.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
document.getElementById("demo").innerHTML =
"Geolocation is not supported by this browser.";
}
function showPosition(position) {
document.getElementById("demo").innerHTML =
"Latitude: " + position.coords.latitude + "<br>" +
"Longitude: " + position.coords.longitude;
}
however, I don't know how to proceed from here. (TT)

navigator.geolocation.getCurrentPosition/watchPosition is not working in android 6.0

Here is my javascript code :
function getLocation() {
//navigator.geolocation.getCurrentPosition(getCoor, errorCoor, {maximumAge:60000, timeout:30000, enableHighAccuracy:true});
var mobile =jQuery.browser.mobile;
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if(mobile){
watchLocation(function(coords) {
var latlon = coords.latitude + ',' + coords.longitude;
//some stuff
}, function() {
alert("error");
});
} else {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("error");
}
}
}
function watchLocation(successCallback, errorCallback) {
successCallback = successCallback || function(){};
errorCallback = errorCallback || function(){};
// Try HTML5-spec geolocation.
var geolocation = navigator.geolocation;
if (geolocation) {
// We have a real geolocation service.
try {
function handleSuccess(position) {
alert("position:"+position.coords);
successCallback(position.coords);
}
geolocation.watchPosition(handleSuccess, errorCallback, {
enableHighAccuracy: true,
maximumAge: 5000 // 5 sec.
});
} catch (err) {
errorCallback();
}
} else {
errorCallback();
}
}
I have tried both getCurrentPosition and watchPosition.
It's reaching errorCalback() method when control comes to geolocation.watchPosition line.
I am testing in Motorola G 2nd Gen with Android 6 and Google chrome browser and opera mini.
Update 1: When I put alert in error call back function I got error:1; message:Only Secure origins are allowed(see:link).
navigator.geolocation.getCurrentPosition(showPosition, function(e)
{ alert(e); //alerts error:1; message:Only Secure origins are allowed(see: )
console.error(e);
})
Update 2: With the help from g4s8 I am able to findout that the error is because of insecure URL. i.e only accessing with http instead of https.But then also I bypassed that in browser by clicking advanced button.But it will prompt for Do you want to allow location, which I don't want..is there any way to access location without prompting it?
Your page should be served over https to access geolocation API.
See Geolocation API Removed from Unsecured Origins
Starting with Chrome 50, Chrome no longer supports obtaining the user's location using the HTML5 Geolocation API from pages delivered by non-secure connections
...
It is an important issue as it will directly impact any site that requires use of the geolocation API and is not served over https
To fix this serve your page over https or on localhost.
Thank you...Is there any way to bypass it??
You can try to use some geolocation services, e.g.
geoip2, Geolocation request
how to use them? can you show an example?? from those two can i access user location without knowing them?
GeoIP2 detect you location by ip address. You can obtain country (geoip2.country()) and city (geoip2.city) with js lib:
<script src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js" type="text/javascript"></script>
Here https://dev.maxmind.com/geoip/geoip2/javascript/ you can find full documentation.
Google maps geolocation is google service, so you need to get api key first. Then you can send POST request with json parameters to https://www.googleapis.com/geolocation/v1/geolocate?key=API_KEY and get the response:
{
"location": {
"lat": 51.0,
"lng": -0.1
},
"accuracy": 1200.4
}
where location is the user’s estimated latitude and longitude, in degrees,
and accuracy is the accuracy of the estimated location, in meters.
Full json parameters defenition you can find in "Request body" section here https://developers.google.com/maps/documentation/geolocation/intro#overview
Also you can find useful those answers: getCurrentPosition() and watchPosition() are deprecated on insecure origins
using IP it provides only country and city..??
Yes, only this.
will it provide physical location like how getCurrent Position provides??
No, you can't get physical location, because it can be accessed only via gelocation API, that was restricted in insecure context.
Also you have one more option. You can host only one page (that access geolocation API) on https server, and redirect from this page to your http site with user location in get parameters.
/* https page */
navigator.geolocation.getCurrentPosition(function (result) {
window.location.href = "http://your.site.com/http-page?lat=" + result.latitude + "&long=" + result.longitude;
});

Alternatives to getCurrentposition?

I have been working on an app that uses the getCurrentPosition(), but that doesn't work anymore in the latest version of Chrome, see:
Deprecating Powerful Features on Insecure Origins
So my code here doesn't work in latest stable version of Chrome:
var latitude = 0;
var longitude = 0;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
$("#data").html("latitude: " + latitude + "<br>longitude: " + longitude);
});
}
What are alternatives to getting the user's position with HTML Geolocation API? Any thoughts?
I'm grappling with this myself. If HTTPS is not an option for you, then maybe add a fallback for Chrome where you prompt the user to submit their address. Then have your app geocode it.

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

Get latitude and longitude of user in PHP or JavaScript for use in PHP

I have an Android app which gets the user's location (latitude and longitude). The latitude and longitude is used to query a database via a web service.
I am in the process of developing a website which will be another gateway into the backend. In order to make the website useful I need to get the latitude and longitude of the user, as the results are sorted by distance (i.e. distance from user's location to location of returned data which is a bar/restaurant).
So how do I get the latitude and longitude of the user?
It is not possible via PHP directly although if you are creating a website you can use the javascript geolocation API to query the browser about what it knows about the users current location:
<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 + "<br>Longitude: " + position.coords.longitude;
}
</script>
I have simply copied the code example from w3 schools vertabrim.
Source:
http://www.w3schools.com/html/html5_geolocation.asp

Categories