I see return data in console but
data.results[0].address_components[4].long_name;
I didn't take data when is test undefined but
x.innerhtml = data.results[0].address_components[4].long_name;
I see city name.
How can I do it?
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
var x = document.getElementById("demo");
var sonuc;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} 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 locAPI="https://maps.googleapis.com/maps/api/geocode/json?latlng="+position.coords.latitude+","+position.coords.longitude+"&key=xxxxxxxxxxxxxxhnfV2NWg&sensor=false";
$.get({
url:locAPI,
success:function(data){
console.log(data);
sonuc=data.results[0].address_components[4].long_name;// i didn' taka data
}
});
x.innerHTML=sonuc;
$.get("giden.php",{"city":sonuc},function(get_veri){
$(".veri").text(get_veri) });
//x.innerHTML=locAPI;
}
If I understand correctly, you're not sure why you are able to console.log(data) in your success callback function but when you try to render the data.results[0].address_components[4].long_name; to your html it renders undefined.
The reason why this is happening is because your success callback is asynchronous and you are appending the sonuc value before the success callback get's fired. What you should do is abstract out the logic for appending data.results[0].address_components[4].long_name; to your html into another function. This new function should be executed in your success callback. This way you are only setting x.innerHTML once you have a successful request and have actual data.
See the code below.
$.get({
url:locAPI,
success:function(data){
renderWhenDataIsValid(data)
}
});
function renderWhenDataIsValid(data){
sonuc=data.results[0].address_components[4].long_name;
x.innerHTML=sonuc;
$.get("giden.php",{"city":sonuc},function(get_veri){
$(".veri").text(get_veri)
});
}
I've also added a working example on jsfiddle you just need to supplement your API key.
Related
I am having this piece of code that takes the user location every 5 seconds.
<div id="geo" onLoad=""></div>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
//Refresh the data
setTimeout(getLocation, 5000);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var obj = { lat: position.coords.latitude, long: position.coords.longitude };
var myJSON = JSON.stringify(obj);
document.getElementById("geo").innerHTML = myJSON;
}
getLocation()
</script>
And it prints correctly in the HTML file it is placed in.
The problem is that when I try to reach and parse it comes up with the HTML and I cannot get the result I need.
I have tried adding different headers to the file but with no luck. The one thing I can think of is somehow throwing the results in a PHP file and then just echoing the results there as plain text.
Do you think that this is possible or there is a better idea for achieving JSON in plain text and not HTML?
UPDATE
This is what I am getting when I am calling the HTML file
And this is how I want it to be (if i echo it with PHP)
I don't think you need JSON. You output the position coordinates directly:
document.getElementById("geo").innerHTML = 'lat: ' + position.coords.latitude + ', long: ' + position.coords.longitude;
Have a small javascript piece of code which calls navigator.geolocation.
I have an if statement, which works, to show the latitude and longitude if the user the user allows the call. However, the else section is not running.
If I run the code below I get prompted by the browser to allow; if I allow it then coordinates are shown. However, if I hit block instead nothing happens even though there is an else section.
<body>
<br> <p id="ChangeSring">Test</p>
<script>
var x = document.getElementById("ChangeSring");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(SavePosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
document.cookie = 'location=false;path=/form_handler';
}
function SavePosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
document.cookie = 'location=true;path=/form_handler';
document.cookie = 'latitude='+ position.coords.latitude +';path=/form_handler';
document.cookie = 'longitude='+ position.coords.longitude +';path=/form_handler';
}
</script>
<form action="/form_handler" _lpchecked="1">
Enter value:
<input type="text" name="SomeVar"><br>
<input type="submit" value="search">
</form>
</body>
You cannot use else to check for permissions.
The navigator method getCurrentPosition takes a success and error callbacks.
The error callback will be called if permission is denied.
if (navigator.geolocation) { // this checks if navigator is supported at all
navigator.geolocation.getCurrentPosition(console.log, () => {
console.log('Permission denied')
});
} else {
console.log('Geolocation is not supported by this browser.');
}
getCurrentPosition takes a success and an error function.
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition#Example
function errorGettingPosition(positionError) {
x.innerHTML = "Geolocation is not supported by this browser.";
document.cookie = 'location=false;path=/form_handler';
}
navigator.geolocation.getCurrentPosition(SavePosition, errorGettingPosition)
That if-else statement is checking if navigator.geolocation it's not undefined(and it's not even if you don't want the browser to know your location) follow the other answers to properly handle permission
Here is my code, I have included following .js files, onpage load it is giving error "ReferenceError: CryptoJS is not defined" why does it give that error when already js references are added. I am making a sharepoint-2013 app using office 365.
<script type="text/javascript" src="../Scripts/sha1.js"></script>
<script type="text/javascript" src="../Scripts/hmac-sha1.js"></script>
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
(function () {
// This code runs when the DOM is ready and creates a context object which is
// needed to use the SharePoint object model
$(document).ready(function ()
{
getUserName();
$("#button1").click(function()
{
paraupdate();
});
});
// This function prepares, loads, and then executes a SharePoint query to get
// the current users information
function paraupdate()
{
var str=""+$("#textbox1").val();
alert(""+str);
var message = str+"json539ff0f815ca697c681fe01d32ba52e3";
var secret = "<my private key>";
var crypto = CryptoJS.HmacSHA1(message, secret).toString();
alert("crypto answer is " + crypto);
var siteurl="http://pnrbuddy.com/api/station_by_code/code/"+str+"/format/json/pbapikey/539ff0f815ca697c681fe01d32ba52e3/pbapisign/"+crypto;
$.ajax({
url: siteurl,
type: "GET",
dataType: 'json',
success: function (data) {
alert("IN Success");
alert(""+data.station_by_code);
},
error: function (error) {
alert("IN Error");
alert(JSON.stringify(error));
}
});
}
function getUserName()
{
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess()
{
$("#label1").html("Enter Station Code : ");
$("#button1").val("CLICK");
}
// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
})();
include core-min.js before sha256.js
There are one of two forms for fixing this:
1: Manual Load, i have more success with this pattern:
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js", execOperation);
}
);
Example:
$.getScript("~hostUrl/_layouts/15/SP.RequestExecutor.js", getListDataREST);
2: Script on Demand:
SP.SOD.executeFunc('sp.userprofiles.js', 'SP.ClientContext', loadUserData);
This SharepointExchange posting, gives the usual JSOM implementation for most AppParts: Jquery is not firing on Page load SharePoint 2013
Error solved I added online references instead,
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha1.js"></script>
Maybe is too late, but:
var CryptoJS = require('crypto-js');
var hash = CryptoJS.HmacSHA256("Message", "secret");
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
console.log(hashInBase64); // qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=
Works fine in node.js.
My MVC Controller is getting hit twice on page load, and I am stumped on how to solve this problem.
I'm using navigator.geolocation.getCurrentPosition in my Layout page, and that passes the latitude and longitude to my controller.
I have RenderAction in a div, just in case the user has JavaScript disabled, as some people still do
:-(
This is what is causing my problem:
The RenderAction is getting rendered 1st and hitting the controller. Then, the AJAX request is firing and hitting the controller.
So my controller is getting hit twice per request.
Is there something I'm missing which will stop that, because at the moment, all I can think of is to remove the render action from the page.
Code:
<div class="dvWeather">
#{ Html.RenderAction("PvCurrentWeatherConditions", "Weather"); }
</div>
if (navigator.geolocation) {
// alert("Geo-Enabled");
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var aj = "gl";
$.ajax({
url: '#Url.Action("PvCurrentWeatherConditions", "Weather")',
type: 'get',
data: {
lat: lat,
lon: lon,
aj: aj
},
success: function (result) {
$('.dvWeather').html(result);
}
});
}
public PartialViewResult PvCurrentWeatherConditions(string lat, string lon, string aj)
{
if (Request.IsAjaxRequest())
{
try
{
//TODO create Viewmodel
GeoCoordinate gc = new GeoCoordinate();
var latitude = gc.Latitude = Convert.ToDouble(lat);
var longitude = gc.Longitude = Convert.ToDouble(lon);
string latlon = latitude + "," + longitude;
var displayCurrentConditions = _igcc.CurrentConditions(latlon);
return PartialView("pvCurrentWeatherConditions");
}
catch (FormatException)
{
//TODO get ip address
return PartialView("pvLocationBasedOnIpAddress");
}
catch (Exception)
{
return PartialView("pvError");
}
}
return PartialView("pvLocationBasedOnIpAddress");
}
Perhaps use another method for checking if the visitor has javascript disabled, like noscript:
<noscript>
<meta http-equiv="refresh" content="[URL]?java=off">
</noscript>
then handle the querystring in a new action.
You don't have to remove the Render action. Just make another (negative) check in the div:
<div class="dvWeather">
<script type="text/javascript>
//if (!navigator.geolocation) { : Edit
if (navigator.geolocation == null) {
#{ Html.RenderAction("PvCurrentWeatherConditions", "Weather"); }
}
</script>
</div>
Edit:
if (navigator.geolocation != null) {
// alert("Geo-Enabled");
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
This way only one call will be made.
Hope it helps.
I'm trying to retrieve the 2 attributes of seprated function and I debug there values before the end of the function and they have a value but the return value is alwas undifined I don't know why !!
the .js file
function STAAPlanlat(){
alert ("the function");
if (navigator.geolocation) {
//we supposed to call the handlers of the expections
navigator.geolocation.watchPosition(function(position) {
alert("show position ");
// x.innerHTML="Latitude: " + position.coords.latitude +"<br />Longitude: " + position.coords.longitude;
var lat=position.coords.latitude;
var lan=position.coords.longitude;
//x.innnerHTML=out
alert(lat+"<"+lan);
return lan;
});
} else {
alert("error");
}
}
I got the alert with the values of the lan and lat
but when I call on separated file it return undefined return value
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="STAAP1.2.js"> </script>
<script type="text/javascript">
function test(){
var out=STAAPlanlat();
document.getElementById("STAAPlanlat").value = "lan is"+out;
//document.writeln("lan is"+out);
}
</script>
</head>
<body>
<p id="STAAPlanlat">Test the division</p>
<button onclick="test()">STAAPlanlat()</button>
<button onClick="alertme()" >Alert</button>
</body>
</html>
Cause you're not returning it from the main function, you're returning it from the embedded anonymous function which isn't doing anything with it. Do this:
function STAAPlanlat(){
var lat;
var lan;
alert ("the function");
if (navigator.geolocation) {
//we supposed to call the handlers of the expections
navigator.geolocation.watchPosition(function(position) {
alert("show position ");
// x.innerHTML="Latitude: " + position.coords.latitude +"<br />Longitude: " + position.coords.longitude;
lat=position.coords.latitude;
lan=position.coords.longitude;
//x.innnerHTML=out
alert(lat+"<"+lan);
});
return lan;
}
else
alert("error");
}
You are returning in the anonymous function and this value is never assigned to anything. You can do what you want with a callback.
// untested code, hope it works
function STAAPlanlat(callback){
alert ("the function");
if (navigator.geolocation) {
navigator.geolocation.watchPosition(function(position) {
var lat=position.coords.latitude;
var lan=position.coords.longitude;
callback(lat, lan);
});
}
else{
alert("error");
}
}
And your test function...
function test(){
var out;
STAAPlanlat(function(lat, lon) { out = lat; });
}
because function STAAPlanlat doesn't return any value. your anonymous function returns lan but it is asynchronous callback.
add this before return lan;:
document.getElementById("STAAPlanlat").value = "lan is" + lan;