javascript argument not passing through a function - javascript

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>

Related

Javascript - Save Geolocation Coordinates

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);
}

Getting error Geocoder failed while fetching current location using JavaScript

I am getting the following error while trying to fetch current location using Google Maps API.
Error:
Geocoder failed
I am providing my code below.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
function getDefaultLocation(){
setTimeout(function(){
var geocoder='';
geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
console.log("Geocoder failed");
}
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){
if (results[1]) {
var indice=0;
for (var j=0; j<results.length; j++){
if (results[j].types[0]=='locality'){
indice=j;
break;
}
for (var i=0; i<results[j].address_components.length; i++){
if (results[j].address_components[i].types[0] == "locality") {
city = results[j].address_components[i];
}
if(results[j].address_components[i].types[0] == "administrative_area_level_1"){
region = results[j].address_components[i];
}
if (results[j].address_components[i].types[0] == "country"){
country = results[j].address_components[i];
}
if(results[j].address_components[i].types[0] == "route"){
locality=results[j].address_components[i];
}
}
}
// console.log('final result',city.long_name,region.long_name,country.long_name,locality.long_name);
var city=city.long_name;
var country=country.long_name;
var locality=locality.long_name;
document.getElementById('bindCon').innerHTML=country; document.getElementById('bindCit').innerHTML=city; document.getElementById('bindloc').innerHTML=locality;
}else{
console.log("No results found");
}
}else{
console.log("Geocoder failed due to: " + status);
}
})
}
},5000);
}
The above code is working properly in localhost but while putting this into my testing site (http://xxxx.com) the above error is coming. Here I need to fetch all the required data.

How to pass javascript alert message value to label in asp.net

I had implemented geolocation , wherein browser gets location of user.
In this code i'm getting geolocation of user through browser ,but it display location using javascript alert message.
I just want to pass alert message value to label or hiddenfield in ASP.Net & doesn't want to run alert message
My javascript code as follows.
<script type="text/javascript">
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() {
alert("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
alert(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_1") {
//this is the object you are looking for
city = results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
document.getElementById('<%=Label1.ClientID %>').innerHTML = city;
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
If you want to store the value in a hidden field replace
alert(results[0].formatted_address)
with
//hdnField is the ID of your asp:HiddenField object
var hiddenField = document.getElementById("<%= hdnField.ClientID %>")
hiddenField.value = results[0].formatted_address;

Find address recursively from latitudes and longitudes in google map api

I have some latitudes and longitudes i want to find out their addresses.
function OnSuccess(response) {
showLatLng(0, JSON.parse(response.d).Table, JSON.parse(response.d).Table.length);
}
Where JSON.parse(response.d).Table contains the result set.
function showLatLng(index, resultSet, totalLen) {
var lat = resultSet[index].x;
var lng = resultSet[index].y;
var latlng = new google.maps.LatLng(lat, lng);
new google.maps.Geocoder().geocode({ 'latLng': latlng },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var z = " <tr>" +
"<td>" + results[0].formatted_address + "</td>" +
"</tr>";
$("#result").append(z);
if (index < totalLen) {
showLatLng(index + 1, resultSet, totalLen);
}
}
}
});
}
This code is working only 4 to 5 times then stops and no error in firebug.
Please give me a better way to do this.
EDIT:
Lucas You are absolutely right.
Previously I have used loop with timeout as below
$.each(JSON.parse(response.d).Table, function (index, value) {
setTimeout(function () {
showLatLng(index , value.x, value.y);
}, (index + 1) * 7000);
});
But for some reason (because I think it is working on async call) it is skipping some results.
pass Latitude and Longitude value to script
function GetAddress() {
var lat = parseFloat(document.getElementById("txtLatitude").value);
var lng = parseFloat(document.getElementById("txtLongitude").value);
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert("Location: " + results[1].formatted_address);
}
}
});
}

Bring out variable from function on javascript [duplicate]

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;
}
}

Categories