I get the wrong latitude and longitude with phonegap geolocation - javascript

i'm using phone gap and I got the geolocation working like so:
function onDeviceReady() {
//navigator.geolocation.getCurrentPosition(onSuccess, onError);
var options = { frequency: 3000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
function onSuccess(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + lat + '<br />' +
'Longitude: ' + long + '<br />' +
'<hr />' + element.innerHTML;
}
But I get the wrong latitude and longitude when testing in xCode. Is that normal?
Thanks

I believe you can go to the Debug -> Location option in the iOS simulator to change the GPS co-ordinates.

Related

Location and weather based image search API for weather app

I am making a basic web-based weather app, which detects the current weather conditions in the user's location. My current code so far does work, but is missing an important feature - I want the background of the web page to change according to the user's location and weather conditions. For instance - if a user is in New York and the weather is sunny, I would like to display any New York based popular image(ex: Times Square) along with sunny skies as the body background. I've searched several APIs but haven't found any that meets my needs.
In my current code, I'm using IPInfo.io to get the user's location and OpenWeatherMap to get the weather conditions.
This pen has my code (NOTE - code for units hasn't been added yet), and here's the JS bit -
var lat = 0.0,
lon = 0.0;
var testURL = 'http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=2de143494c0b295cca9337e1e96b00e0';
var myURL = 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&appid="ae0acb60e8db4952e081c2fb470a1b23"';
var city = '',
state = '',
country = '',
postal = 0;
//if (navigator.geolocation) {
// /* geolocation is available */
// navigator.geolocation.getCurrentPosition(function (position) {
// lat = position.coords.latitude;
// lon = position.coords.longitude;
// console.log("Latitude = " + lat);
// console.log("Longitude = " + lon);
//
// display(position.coords.latitude, position.coords.longitude);
// });
//
//} else {
// /* geolocation IS NOT available */
// $("#jumbotron").html("geolocation not available");
//
//}
//get co-ordinates using ipinfo.io
$.getJSON('http://ipinfo.io', function (data) {
console.log(data);
var loc = data.loc;
lat = loc.split(",")[0];
lon = loc.split(",")[1];
display(lat, lon);
city = data.city;
state = data.region;
country = data.country;
postal = parseInt(data.postal, 10);
})
function display(x, y) {
$("#pos1").html("<b>" + x + "</b>");
$("#pos2").html("<b>" + y + "</b>");
}
//function to calculate wind direction from degrees
function degToCompass(num) {
//num = parseInt(num, 10);
console.log("Inside degtocompass = " + num);
var val = Math.floor((num / 22.5) + 0.5);
var arr = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"];
return arr[(val % 16)];
}
//function to return current temperature
function convertTemp(currTemp) {
//get celsius from kelvin
return Math.round(currTemp - 273.15);
}
$("button").click(function () {
console.log("In Latitude = " + lat);
console.log("In Longitude = " + lon);
//prepare api call
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&appid=ae0acb60e8db4952e081c2fb470a1b23',
//url: testURL,
type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc
data: {}, // Additional parameters here
dataType: 'json',
success: function (data) {
console.log(data);
//---------get the clipart---------------
var picLink = 'http://openweathermap.org/img/w/';
var picName = data.weather[0].icon;
picLink += picName + ".png";
$("#picture").empty().append('<img src="' + picLink + '">');
//----------get the temperature-----------
var curTemp = convertTemp(data.main.temp);
console.log("Current temp = " + curTemp);
//$("#temp").empty().append("<b>" + curTemp + "</b>");
$("#picture").append("<b>" + curTemp + "</b>");
//----------get the place----------------------
var area = city + ", " + state + ", " + country;
$("#area").empty().append("<b>" + area + "</b>");
//----------get weather conditions------------
$("#conditions").empty().append("<b>" + data.weather[0].description + "</b>");
//----------get wind speed------------
//get wind direction
var windSpeed = degToCompass(data.wind.deg);
//add wind speed
windSpeed += ' ' + data.wind.speed;
//display wind speed
$("#wind-speed").empty().append("<b>" + windSpeed + "</b>");
},
error: function (err) {
alert(err);
},
beforeSend: function (xhr) {
//xhr.setRequestHeader("X-Mashape-Authorization", "32ROUuaq9wmshfk8uIxfd5dMc6H7p1lqdZSjsnXkB5bQtBteLK"); // Enter here your Mashape key
}
});
});
Well... First of all there is no need to use WebServices, but you can't do it without any API. As I can see you use openweathermap API . As far as I know this API returns both longitude and latitude, so you can use these values as input to another request to a photo API (like flickr) to get the image you want. Moreover openweathermap API returns city name which can make your photo request even more accurate.

Out of the box browser Geolocation is slightly less accurate then production websites

I'm checking out my Geolocation on a laptop.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lon1 = position.coords.longitude;
});
}
lat and lon are giving slightly different outputs then what the same browser is outputting on a site like http://whereamirightnow.com/
Are they using some Google libraries to improve the accuracy or something?
Turns out that using this gave me the more precise longitude and latitude that other sites were producing by enabling high accuracy. Looks like Leaflet did it under the hood which confused me.
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log('Latitude : ' + crd.latitude);
console.log('Longitude: ' + crd.longitude);
console.log('More or less ' + crd.accuracy + ' meters.');
};
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};
navigator.geolocation.getCurrentPosition(success, error, options);

how to append to div id

i know it is easy and silly question but how can i show the lat and lng append into div id instead of giving me on alert.Can i do something like that !!
document.getElementById("here").innerHTML = ("lat: +lat+"lng: " + lng)
<!DOCTYPE>
<html>
<meta name="viewport" content="width=device-width,
initial-scale=1, maximum-scale=1,user-scalable=no">
<head>
<script>
function geolocation(){
<!--checks if geolocation is available -->
var options = { enableHighAccuracy: true};
watchId = navigator.geolocation.watchPosition(onSuccess, onError, options);
<!-- function run if gets the geolocation back -->
function onSuccess(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
alert("lat: " + lat + "lng: " + lng);
}
<!-- this function run if there is any error in geolocation -->
function onError(error){
alert("message: " + error.message);
}
}
geolocation();
</script>
</head>
<body>
<div id="here"></div>
</body>
You may try something like this: Edit: Updated HTML
<div id="location"></div>
<script>
$( document ).ready(function() {
geolocation();
}
function geolocation(){
<!--checks if geolocation is available -->
var options = { enableHighAccuracy: true};
watchId = navigator.geolocation.watchPosition(onSuccess, onError, options);
<!-- function run if gets the geolocation back -->
function onSuccess(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//alert("lat: " + lat + "lng: " + lng);
document.getElementById("location").innerHTML = "lat: " + lat + "lng: " + lng;
}
<!-- this function run if there is any error in geolocation -->
function onError(error){
alert("message: " + error.message);
}
}
</script>
Ok So, I think what you want is this:
div = document.getElementById('here');
div.appendChild(watchId);
Thats how you append to your particular div.
Yes, it's possible, with the property innerHTML you wrote you should solve your problem.
Yes, you definetely can. However, the string you provided is not quoted correctly. Don' t you get an exception in console?
document.getElementById("here").innerHTML = "lat: " + lat + "lng: " + lng;
Using jQuery you can simply do this:
$("#here").text("lat: " + lat + " lng: " + lng");
Or if you want to keep the content of here and append the information at the end:
$("#here").append("lat: " + lat + " lng: " + lng");

Cordova: HTML5 geolocation - find the nearest place from JavaScript array

I have array of places in JavaScript. I need to get gps geolocation from gps sensor (on mobile phone using Apache Cordova).
If GPS accuracy is better than for example 40 meters, I need to do something (set css display:block, change color, ...).
I have this code:
<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/distance.js"></script> <!-- https://github.com/janantala/GPS-distance/blob/master/javascript/distance.js -->
<script type="text/javascript" charset="utf-8">
var interval = 5; // [s]
var timeout = 60; // [s]
/* --------------------------------------------------- */
var latitude = new Array();
var longtitude = new Array();
var nameOfLocation = new Array();
// address 1
// Latitude : 10.20 | Longitude : 30.40
latitude[0] = 10.20;
longtitude[0] = 30.40;
nameOfLocation[0] = "address 1";
// address 2
// Latitude : 40.30 | Longitude : 20.10
latitude[1] = 40.30;
longtitude[1] = 20.10;
nameOfLocation[1] = "address 2";
// ...
/* --------------------------------------------------- */
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
function onDeviceReady() {
console.log('in onDeviceReady()');
$(document).ready(function(){
setInterval(function(i) {
navigator.geolocation.getCurrentPosition(onSuccess, onError, {
maximumAge: 0,
timeout: (timeout*1000),
enableHighAccuracy: true }
);
}, (interval*1000))
});
}
// onSuccess Geolocation
function onSuccess(position) {
console.log('in onSuccess()');
console.log(position.coords.latitude, "position.coords.latitude");
console.log(position.coords.longitude, "position.coords.longitude");
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'Altitude: ' + position.coords.altitude + '<br />' +
'Accuracy: ' + position.coords.accuracy + '<br />' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' +
'Heading: ' + position.coords.heading + '<br />' +
'Speed: ' + position.coords.speed + '<br />' +
'Timestamp: ' + position.timestamp + '<br />';
var place;
var accuracy;
$("#accuracy").html("GPS accuracy " + position.coords.accuracy + " m.");
if (position.coords.accuracy < 40) {
$("#accuracy").css("background-color", "Gray");
for (var i=0; nameOfLocation.length; i++) {
var distance = getDistance(latitude[0], longitude[0], position.coords.latitude, position.coords.longitude);
if (distance <= 25) {
place = i;
accuracy = position.coords.accuracy;
$("#accuracy").css("background-color", "OrangeRed");
} else if (distance <= 20) {
place = i;
accuracy = position.coords.accuracy;
$("#accuracy").css("background-color", "Yellow");
} else if (distance <= 15) {
place = i;
accuracy = position.coords.accuracy;
$("#accuracy").css("background-color", "Green");
}
}
$("#info").html("You are about <strong>" + accuracy + "</strong> meters from location <strong>" + nameOfLocation[i] + "</strong>");
} else {
$("#info").html("");
}
}
// onError Callback receives a PositionError object
function onError(error) {
console.log('in onError()');
console.log(error.code, "error.code");
console.log(error.message, "error.message");
$("#geolocation").html(
'code: ' + error.code + '<br />' +
'message: ' + error.message);
$("#accuracy").css("background-color", "");
}
</script>
</head><body>
<p id="info"></p>
<hr />
<p id="accuracy"></p>
<hr />
<p id="geolocation">GPS ...</p>
</body></html>
I use this JS lib for distance measurement of two GPS locations https://github.com/janantala/GPS-distance/blob/master/javascript/distance.js
I can't use google online gps distance lib. App must work without internet connection.
If I run app it start location gps. After first finding location any next finding take only about 5 seconds and after that stop finding locations (this repeats to infinity). I need permanent searching.
Do you know where is an error?
I'm going to do it well?

Phonegap/AngularJS: Get lat/long from inside function

I am trying to set a couple of global variables from inside a function so that I can use the results in an Angular Ctrl.
I have tried everything I can think of and can't seem to get the variable outside of the function. I know this is probably something simple but just can't figure it out!
Thanks in advance for your help.
onSuccess = function(position) {
lat = position.coords.latitude;
lon = position.coords.latitude;
// alert('Latitude: ' + position.coords.latitude + '\n' +
// 'Longitude: ' + position.coords.longitude + '\n' +
// 'Altitude: ' + position.coords.altitude + '\n' +
// 'Accuracy: ' + position.coords.accuracy + '\n' +
// 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
// 'Heading: ' + position.coords.heading + '\n' +
// 'Speed: ' + position.coords.speed + '\n' +
// 'Timestamp: ' + new Date(position.timestamp) + '\n');
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
// ??????
console.log(getCurrentPosition.lat);
EDIT: This is the controller
I need to get lat and lon in place of the current hard coded versions:
var app = angular.module('presto-map', ["ngResource", "ngSanitize", "google-maps"]);
function mapCtrl ($scope) {
// Initialise the map
$scope.map = {
center: {
latitude: 53.58684546368308,
longitude: -1.5543620512747744
},
zoom: 8
};
}
Pass $window to your controller and set lat lng in your scope.
$scope.getCurrentLocation = function () {
$window.navigator.geolocation.getCurrentPosition(function(position) {
$scope.$apply(function() {
$scope.latitude = position.coords.latitude;
$scope.longitude = position.coords.longitude;
$scope.accuracy = position.coords.accuracy;
});
}, function(error) {
alert(error);
});
}
Else if you want to have some global variables in your app use Services to do so. In Service have all the global data and then access it in your controller by passing the service to controllers.
If you are trying to rich lat variable in console.log, then the problem is that your console.log is called before onSuccess handler.
Update:
var app = angular.module('presto-map', ["ngResource", "ngSanitize", "google-maps"]);
function mapCtrl ($scope, $q, $window) {
function getPosition() {
var deferred = $q.defer();
$window.navigator.geolocation.getCurrentPosition(function(position) {
$scope.$apply(function() {
deferred.resolve({
latitude : latitude,
longitude : longitude,
accuracy : accuracy
});
})
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
// Initialise the map
getPosition().then(function(result) {
$scope.map = {
center: {
latitude: result.latitude,
longitude: result.longitude
},
zoom: 8
};
});
}

Categories

Resources