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;
}
}
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);
}
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()?
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>
I use this to geolocate the user and I need the values of currentLat and currentLon stored in a var:
<script>
window.onload = function() {
var startPos;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
startPos = position;
document.getElementById("currentLat").innerHTML = startPos.coords.latitude;
document.getElementById("currentLon").innerHTML = startPos.coords.longitude;
});
}
};
</script>
I need those values in here:
http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=my_key&radius_units=km&radius=5&lat= XXX &lon= XXX &jsoncallback=?
How do I get the values through jQuery and put them in the URL immediately? What's the quickest way?
Thanks #Manuel but I have used it like this first as I don't need the error function, just to keep it simple so I can understand it but doesn't work?!
$(document).ready(function() {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var JSONURL = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=my_key&format=json&privacy_filter=1&media=photos&tag=london&minwidth=700&has_geo=1&accuracy=11&content_type=1&extras=geo,owner_name,url_m&page=1&radius_units=km&radius=5&"+lat+"&lon="+lon+"&jsoncallback=?";
jQuery.getJSON( JSONURL, getJSONimages);
function getJSONimages(data) {
var htmlString = "";
$.each(data.photos.photo, function(i,item){
var itemTitle = item.title;
});
$('#slideshow').html(htmlString);
$('#slideshow').slideshow({
timeout: 3000,
type: 'random',
fadetime: 2000
});
} }
})
in the var url you'll get find the url with the lat an lon filled in
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var url = 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=my_key&radius_units=km&radius=5&lat='+lat+'&lon='+lon+'&jsoncallback=?';
// console.log(url);
}, function(error) {
console.log("Something went wrong: ", error);
});