I am trying to run a Javascript code to retrieve a device's geolocation. When I try to run the code from the localhost (127.0.0.1) the code runs as expected, opening a pop up to ask the user to enable location services. However, when I try to host this code or access it using the local IP address (192.168.x.y), the code fails with an error
Any ideas as to why it works for localhost and not otherwise.
Here's the JS Code
function geoFindMe() {
var output = document.getElementById("out");
if (!navigator.geolocation){
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
output.appendChild(img);
}
function error() {
output.innerHTML = "Unable to retrieve your location";
}
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, error);
}
Thanks.
Recent versions of Chrome require secure protocols for some features. Fore example a page must be served up httpS for it to be able to obtain the user's geolocation.
The restriction is relaxed for localhost to enable dev/debugging.
Related
I'm trying to build an app using PhoneGap and although I can get the lat and long from my current position using my mobile phone gps, I can't seem to get weather info out of my dark sky api. I don't know what I am doing wrong.
I've tried to use a json script to get the variables lat and long to plug into my api request. There is something I am missing that is needed to bridge the gap.
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'Altitude: ' + position.coords.altitude + '<br />';
var lat = position.coords.latitude;
var long = position.coords.longitude;
getWeatherData(lat, long)}
}
function getWeatherData(lat, long){
var apiKey = "<my API key>";
var exclude = "?exclude=minutely,hourly,daily,alerts,flags";
var unit = "?units=si";
var url = "https://api.darksky.net/forecast/" + apiKey + "/" + lat + "," + long + exclude + unit;
//get darksky api data
$.ajax({
url: url,
dataType: "jsonp",
success: function (weatherData) {
//weather description
var description = weatherData.currently.summary;
$('#weather-description').text(weatherData.currently.summary);
}
});
print(getWeatherData)
}
function print(getWeatherData){
var element = document.getElementById('weather-description');
element.innerHTML = 'Description ' + weatherData.currently.summary + '<br />';
}
</script>
Then in my HTML...
<p id="geolocation">Finding geolocation...</p>
<p id="weather-description">Loading Description...</p>
Actual results, lat and long and altitude are displayed instead of Finding geolocation, but I expected the weather description to be printed where it says Loading description but it is not.
I worked. Thank you to NewToJS for helping me. The problem was I wasn't calling the function. I've been working on this for 4 days I can't believe it works!
I'm running basic code that just outputs the longitude and latitude on the screen or prints an error if something goes wrong.
function getMyLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation, displayError);
}
else {
alert("Oops, no geolaction support");
}
}
function displayLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var h1 = document.getElementById("location");
console.log("hey " + latitude + " " + longitude);
h1.innerHTML += " " + latitude + ", " + longitude;
}
function displayError(error) {
var errorTypes = {
0: "unkown error",
1: "Permission denied by user",
2: "Position is not available",
3: "Request timed out"
};
var errorMessage = errorTypes[error.code];
if(error.code == 0 || error.code == 2) {
errorMessage += " " + error.message;
}
var div = document.getElementById("location");
div.innerHTML = errorMessage;
}
When i run in firefox and internet explorer i get pop-ups asking for permission and the code runs fine. When I use my phone's google chrome browser i get asked for permission and everything works fine. When i try chrome on my desktop I never get asked permission and my error code runs and prints: "Permission denied by user". I've checked in my chrome settings and made sure my hostname is allowed and tried allowing any site to track my physical location but to no avail. What do?
This is a sample javascript code from http://locationdetection.mobi to detect geo location using google API.
(Original zip file contains a php file, html, and this javascript code)
As you see in the code below, on the last part of this javascript code there is one line of code to render the result of location detection to html file.
How to generate result into a text file instead of render to browser?
// this is called when the browser has shown support of navigator.geolocation
function GEOprocess(position) {
// update the page to show we have the lat and long and explain what we do next
document.getElementById('geo').innerHTML = 'Latitude: ' + position.coords.latitude + ' Longitude: ' + position.coords.longitude;
// now we send this data to the php script behind the scenes with the GEOajax function
GEOajax("geo.php?accuracy=" + position.coords.accuracy + "&latlng=" + position.coords.latitude + "," + position.coords.longitude +"&altitude="+position.coords.altitude+"&altitude_accuracy="+position.coords.altitudeAccuracy+"&heading="+position.coords.heading+"&speed="+position.coords.speed+"");
}
// this is used when the visitor bottles it and hits the "Don't Share" option
function GEOdeclined(error) {
document.getElementById('geo').innerHTML = 'Error: ' + error.message;
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(GEOprocess, GEOdeclined);
}else{
document.getElementById('geo').innerHTML = 'Your browser sucks. Upgrade it.';
}
// this checks if the browser supports XML HTTP Requests and if so which method
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}else if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// this calls the php script with the data we have collected from the geolocation lookup
function GEOajax(url) {
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatePage;
xmlHttp.send(null);
}
// this reads the response from the php script and updates the page with it's output
function updatePage() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
document.getElementById("geo").innerHTML = '' + response;
}
}
You can't create text files from the frontend, well at least not without configuring some flags in the browser, so you need to send the data to your backend language, create the file and then download it
I am trying to fetch the current location using the geolocation . A month before it was giving correct location but not am getting different location . I have used the same code as below.
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;
*/ var query = "?latitude="+position.coords.latitude+"&longitude="+position.coords.longitude;
var stateObj = { query: query };
history.pushState(stateObj, "query added", query);
var flag = true;
/*var req = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
req.onreadystatechange=function(){if((r.readyState==4)&&(r.status==200)){ console.log('location was sended to server'); }};
req.open("GET","?latitude="+position.coords.latitude+"&longitude="+position.coords.longitude,true);
req.send(null);
*/
}
Another problem is its fetching the latlong based on isp not on IP. So if i use this code using mobile internet ! It gives latlong of another state. Is there any way to make this work again?
I'm coding a web app which is using by maps. I want to find visitor's location. It is working on firefox but not working on chrome. Chrome says "it is blocked that track your location by this page." How can i fix it for chrome?
function onPositionUpdate(position)
{
var lat = position.coords.latitude;
var lng = position.coords.longitude;
alert("Current position: " + lat + " " + lng);
}
if(navigator.geolocation)
navigator.geolocation.getCurrentPosition(onPositionUpdate);
else
alert("navigator.geolocation is not available");
and now I try this:
function get_location() {
if (geo_position_js.init()) {
geo_position_js.getCurrentPosition(show_map, handle_error);
}
}
function show_map(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("lat:" + latitude + " long:" + longitude);
}
function handle_error(err) {
alert(err.code);
if (err.code == 1) {
// user said no!
}
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(show_map, handle_error);
} else {
error('not supported');
}
When I run this with chrome I get "javascript alert 1" error. It is working on firefox.
Edit: I solve this problem by using html5 geolocation http://www.w3schools.com/html/html5_geolocation.asp
Type on address bar: chrome://settings/content
Some features only be accessible on "secure origins" (such as HTTPS) where the full ancestor chain is also secure.
https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins