I'm trying to get the speed of a device with the Geolocation Webapi, but don't get any value using this code:
var x = document.getElementById("speed");
var xkmh = document.getElementById("speed2");
var y = document.getElementById("accuracy");
var z = document.getElementById("timestamp");
var longitude = document.getElementById("longitude");
var latitude = document.getElementById("latitude");
function testLocation() {
if (navigator.geolocation) {
console.log("geolocation available");
getLocation();
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
alert("gps not supported");
}
}
function getLocation () {
navigator.geolocation.getCurrentPosition(showPosition);
setTimeout(function() {getLocation()}, 500);
}
function showPosition(position) {
console.log(position);
x.innerHTML = position.speed + " m/s";
xkmh.innerHTML = position.speed * 3.6 + " km/h";
y.innerHTML = position.accuracy + " accuracy";
z.innerHTML = position.timestamp + " timestamp";
longitude.innerHTML = position.coords.longitude;
latitude.innerHTML = position.coords.latitude;
console.log("run");
}
testLocation();
Does it only work with showPosition()?
Related
How can i save the coordinates in localstorage so that it shouldn't ask the users every time to allow GPS or Location and a button to clear the localstorage value so it can again ask for coordinates?
FYI:
I am using Praytimes JS to display Muslim prayer times but for each location i have to manually add latitude & longitude of that location.
Below is my code:
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var x = document.getElementById("currentlocation");
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
$('#currentlocation').html("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
$('#currentlocation').html(results[0].formatted_address);
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_2") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
$('#currentlocation').html(city.short_name + " " + city.long_name)
} else {
$('#currentlocation').html("No results found");
}
} else {
$('#currentlocation').html("Geocoder failed due to: " + status);
}
});
}
</script>
<p id="currentlocation"></p>
<script type="text/javascript" src="http://praytimes.org/code/v2/js/PrayTimes.js"></script>
<script type="text/javascript">
function loadTable(position) {
prayTimes.setMethod('MWL');
var date = new Date(); // today
var times = prayTimes.getTimes(date, [position.coords.latitude, position.coords.longitude]);
var list = ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha', 'Midnight'];
var html = '<table id="timetable">';
html += '<tr><th colspan="2">'+ date.toLocaleDateString()+ '</th></tr>';
for(var i in list) {
html += '<tr><td>'+ list[i]+ '</td>';
html += '<td>'+ times[list[i].toLowerCase()]+ '</td></tr>';
}
html += '</table>';
document.getElementById('table').innerHTML = html;
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(loadTable);
}
</script>
Define an object with the informations of the coordinates:
var coordinatesObject =
{
lat: position.coords.latitude,
lng: position.coords.longitude
}
Save it in the local storage:
localStorage.setItem('coordinates',
JSON.stringify(coordinatesObject));
Get it:
let objFromLocalStorage =
localStorage.getItem('coordinates');
var CACHED_POSITION = "CACHED_POSITION";
var x = document.getElementById("currentlocation");
var geocoder;
(function () {
if (navigator.geolocation) {
try {
var position = JSON.parse(window.localStorage[CACHED_POSITION]);
if (position) {
successFunction(position);
return;
}
} catch (e) {
}
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
})();
//Get the latitude and the longitude;
function successFunction(position) {
window.localStorage[CACHED_POSITION] = JSON.stringify(position);
var lat = position.coords.latitude;
var lng = position.coords.longitude;//Save to cache
codeLatLng(lat, lng);
}
var GOOGLE_API_KEY = "mykey";
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
}
function errorFunction() {
alert ("Geocoder failed");
}
function reverseGeoCoding(lat, lng) {
var geoCodingUrl = "https://maps.googleapis.com/maps/api/geocode/json? latlng=" + lat + "," + lng + "&key=" + GOOGLE_API_KEY
return $.get(geoCodingUrl)
}
reverseGeoCoding(lat, lng)
.then(function(data) {
var address = results[6].formatted_address;
if (address == "Mumbai, India") {
window.location = "url";
}
if(address == "Bangalore, India"){
window.location = "url";
}
if(address == "Jaipur, India") {
window.location = "url";
}
else{
window.location = "url";
}
});
I wanted to utilise this script to redirect users based on the address retrieved by making use of Google's API. However, console error message says variable 'lat' cannot be found?
You should do this:
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
reverseGeoCoding(lat, lng).then(function(data) {
var address = results[6].formatted_address;
if (address == "Mumbai, India") {
window.location = "url";
}
if(address == "Bangalore, India"){
window.location = "url";
}
if(address == "Jaipur, India") {
window.location = "url";
}
else{
window.location = "url";
}
})
}
Or declare it as global variables
i'm trying to get a user's current city plus whatever argument that's being passed through getCity function when clicked but i'm getting undefined for 'x' variable. here's the code..
<button onclick="getCity('burger')">burger</button>
<button onclick="getCity('steak')">steak</button>
<button onclick="getCity('taco')">taco</button>
<script type="text/javascript">
//get city
function getCity(x) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPos);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
//get lat and long
function showPos(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//get address
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'location': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//get city
if (results[0]) {
var city = results[0]['address_components'][2].long_name;
var x = x;
alert(x +" "+ city); // i'm getting undefined + currentcity
}
}
});
}
</script>
i'm getting undefined + currentcity. how do i make it so i get burger + currentcity if i click on burger button?
You second last statement
var x = x;
asssigns an undefined x to x. Both "x"s are undefined.
For your script to work you have to declare a global variable
<button onclick="getCity('burger')">burger</button>
<button onclick="getCity('steak')">steak</button>
<button onclick="getCity('taco')">taco</button>
<script type="text/javascript">
var food;
//get city
function getCity(x) {
if (navigator.geolocation) {
food = x;
navigator.geolocation.getCurrentPosition(showPos);
} else {
//x.innerHTML does not work because x is a string not an element
this.innerHTML = "Geolocation is not supported by this browser.";
}
}
//get lat and long
function showPos(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//get address
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'location': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//get city
if (results[0]) {
var city = results[0]['address_components'][2].long_name;
var x = food;
alert(x +" "+ city);
}
}
});
}
</script>
Another possible solution would be passing it to pass the x to the showPos function.
<button onclick="getCity('burger')">burger</button>
<button onclick="getCity('steak')">steak</button>
<button onclick="getCity('taco')">taco</button>
<script type="text/javascript">
//get city
function getCity(x) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
showPos(position, x);
});
} else {
//x.innerHTML does not work because x is a string not an element
this.innerHTML = "Geolocation is not supported by this browser.";
}
}
//get lat and long
function showPos(position, x) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//get address
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'location': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//get city
if (results[0]) {
var city = results[0]['address_components'][2].long_name;
//var x = food; x is already a parameter of this function so don't declare it again
alert(x +" "+ city);
}
}
});
}
</script>
This question already has answers here:
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 7 years ago.
i have function like below
function showPosition(position) {
latOn = position.coords.latitude;
longOn = position.coords.longitude;
document.getElementById('lat').value=latOn;
document.getElementById('long').value=longOn;}
var locationx = new google.maps.LatLng(latO,longO);
latlng = locationx;
i want bring out "latOn and longOn" to
var locationx = new google.maps.LatLng('here');
help me please,...
thnks before
here you go: EDIT:
var x = document.getElementById("demo");
var locationx = new google.maps.LatLng(-7.2574719, 112.7520883);
latlng = locationx;
var myLocation;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
latOn = position.coords.latitude;
longOn = position.coords.longitude;
document.getElementById('lat').value = latOn;
document.getElementById('long').value = longOn;
myLocation = { latOn: latOn, longOn: longOn };
}, showError);
}
else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
Now every change of the location the variable myLocation will be the new location
If you want getLocation to return a value use:
var x = document.getElementById("demo");
var locationx = new google.maps.LatLng(-7.2574719, 112.7520883);
latlng = locationx;
var myLocation = getLocation();
function getLocation() {
if (navigator.geolocation) {
var location;
navigator.geolocation.getCurrentPosition(function (position) {
latOn = position.coords.latitude;
longOn = position.coords.longitude;
document.getElementById('lat').value = latOn;
document.getElementById('long').value = longOn;
location = { latOn: latOn, longOn: longOn };
}, showError);
}
else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
if (location) {
return location;
}
}
I'm trying to make use of HTML5 geolocation for a project I'm working on.
It seems pretty straighforward to get the Lat and Long of where a user is, via geolocation.
Problem is, I need to convert this to a UK postcode, and am strugging as I'm trying to learn javascript.
The code I have working is:
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function displayPosition(position) {
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
var Lat = position.coords.latitude;
var Long = position.coords.longitude;
var inputField = document.getElementById("addressInput");
inputField.value = Lat + Long;
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
I've found this site, whihc does exactly the kind of thing I want to achieve:
http://www.latlong.net/Show-Latitude-Longitude.html
Can anyone give me some tips on how to get this working?
Any advice would be great
thanks in advance
=========================
Amended code:
//var long = '50.**************', lat = '0.**************'
var Lat='';
var Long='';
var coordsObj = {coords:{latitude:Lat, longitude:Long}};
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function displayPosition(position) {
console.log(position, position.coords)
console.log("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
var Lat = position.coords.latitude;
alert(Lat);
var Long = position.coords.longitude;
alert(Long);
var inputField = document.getElementById("addressInput");
inputField.value = Lat + Long;
return [Lat, Long];
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
function reverseGeoLookup(lon, lat) {
var req = new XMLHttpRequest()
req.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true)
req.onreadystatechange = function() {
if(req.readyState == 4) {
var result = JSON.parse(req.response).results
for(var i = 0, length = result.length; i < length; i++) {
for(var j = 0; j < result[i].address_components.length; j++) {
var component = result[i].address_components[j]
if(~component.types.indexOf("postal_code")) {
var out = document.getElementById('output')
out.innerHTML += component.long_name
}
}
}
}
}
req.send()
}
var latlng = displayPosition(coordsObj)
reverseGeoLookup.apply(this, latlng)
There's now a free UK government alternative to the other options listed here. Go to http://postcodes.io/ to see the details of the API and examples. It also supports reverse lookups which is what you're after
You could use the Google Maps reverse geocoding API. This allows you to map a lat, long pair to a set of addresses. For example:
function reverseGeoLookup(lon, lat) {
//make a ajax request -- in prod just use whatever libraryyou have to provide this
//probably jquery's $.get
var req = new XMLHttpRequest()
//put the longitude and latitude into the API query
req.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true)
//this is just the result callback -- it's the function arg to $.get, essentially
req.onreadystatechange = function() {
if(req.readyState == 4) {
//again jquery will parse for you, but we want the results field
var result = JSON.parse(req.response).results
//the maps API returns a list of increasingly general results
//i.e. street, suburb, town, city, region, country
for(var i = 0, length = result.length; i < length; i++) {
//each result has an address with multiple parts (it's all in the reference)
for(var j = 0; j < result[i].address_components.length; j++) {
var component = result[i].address_components[j]
//if the address component has postal code then write it out
if(~component.types.indexOf("postal_code")) {
var out = document.getElementById('output')
out.innerHTML += component.long_name
}
}
}
}
}
//dispatch the XHR... just use jquery
req.send()
}
I put this example into a js fiddle too, here.
Hope this helps.
I've made some changes to kieran's fiddle to more to help fully answer the question of getting a UK postcode from an html5 geolocation.
var x=document.getElementById("output");
getLocation();
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.watchPosition(reverseGeoLookup);
}
else
{
x.innerHTML="Geolocation is not supported by this browser.";
}
}
function reverseGeoLookup(position) {
console.log(position);
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var req = new XMLHttpRequest()
req.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true)
req.onreadystatechange = function() {
if(req.readyState == 4) {
var result = JSON.parse(req.response).results
for(var i = 0, length = result.length; i < length; i++) {
for(var j = 0; j < result[i].address_components.length; j++) {
var component = result[i].address_components[j]
//console.log(component.long_name);
if(~component.types.indexOf("postal_code")) {
var out = document.getElementById('output');
out.innerHTML = 'Approximate Post Code for your location is ' + component.long_name;
return false;
}
}
}
}
}
req.send()
}
http://jsfiddle.net/ef72Q/28/