Get position coordinates for an ajax request - javascript

Currently working on a weather web-app for iOS. I'm trying to get the coordinates of the user and put the latitude and longitude in my Ajax request (on the api Wunderground) .
Here's my code (EDIT):
<script type="text/javascript">
$(document).ready(function() {
navigator.geolocation.getCurrentPosition(getLocation, unknownLocation);
function getLocation(pos)
{
var lat = pos.coords.latitude;
var lon = pos.coords.longitude;
$.ajax({
url : "http://api.wunderground.com/api/ApiId/geolookup/conditions/q/"+ lat +","+ lon +".json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
}
function unknownLocation()
{
alert('Could not find location');
}
});
</script>
As you can see I "simply" have to create 2 vars lat and lon and add them in my request. I tried a lot of variants but I can't get this code working.
Any idea of what I'm doing wrong ?
Thank you very much !

Your variable declarations are in the middle of the .ajax call, and are making the JavaScript structure invalid. Also, I'm not sure why you're using "function($)", normally with jQuery the $ is reserved and shouldn't be used as a function parameter.
<script type="text/javascript">
$(document).ready(function() {
navigator.geolocation.getCurrentPosition(onPositionUpdate);
});
function onPositionUpdate(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
$.ajax({
url : "http://api.wunderground.com/api/ApiId/geolookup/conditions/q/"+lat+","+lon+".json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
}
</script>

Related

How do i access a filemaker script with javascript in Web Viewer using Apple Mapkit?

I have Filemaker 18 with a Web Viewer using Apple Maps. When I move a pin on the map I want to send the coordinates to a filemaker script that writes to 2 fields. The problem is I can not trigger the script. The database is hosted on a FM Server 18. I have tried these 3 approaches but I am not even able to run a simple "Hello" script. The database name is WEBMAP.fmp12 . Here is how I have tried to run the script. I get no response:
1)
var theURL = "fmp://$/" & Get ( FileName ) & "?script=Hello&param=" + lat +"|"+ long;
window.location = theURL;
2)
var theURL ="fmnet://ip_address_of_server/WEBMAP.fmp12?script=Hello&param=" + lat +"|"+ long;
window.location = theURL;
3)
var theURL = "window.location = "fmp://$/WEBMAP.fmp12?script=Hello&param=" + lat +"|"+ long;
window.location = theURL;
In fact I notice that when I have anything after showing a popup (then I want to run the script) the map is blank whatever I add like "alert("hello").
Here is my js file in Filemaker 18:
var message = document.getElementById("message");
var center = new mapkit.Coordinate(x,y); //
mapkit.init({
authorizationCallback: done => {
done(
"<<$$JWT.TOKEN>>"
);
}
}); //alert("<<$$JWT.TOKEN>>");
var map = new mapkit.Map("map", {
showsScale: mapkit.FeatureVisibility.Visible,
center: center
});
var marker = new mapkit.MarkerAnnotation(map.center, {
draggable: true,
selected: true,
title: "Dra meg og slipp!"
});
marker.addEventListener("drag-start", function(event) {
// No need to show "Drag me" message once user has dragged
// event.target.title = "";
// Hide message
message.style.display = "none";
});
marker.addEventListener("drag-end", function() {
// center map to marker when moved
map.setCenterAnimated(marker.coordinate);
// hide message after seconds
window.setTimeout(function () {
message.style.display = "none";
}, 3550);
// message to show after move
var lat = marker.coordinate.latitude;
var long = marker.coordinate.longitude;
var message = document.getElementById('message');
message.innerHTML = "<p>Vi har lagret posisjonen</p>Latitude: " + lat + " <br />Longitude: " + long;
message.style.display = "block";
//alert("Hello"); ** this alert works!! **
//var test = ‘Hello World!’; alert(test); ** this line gives me a blank map just adding a "var statement" **
var theURL = "fmp://$/" & Get ( FileName ) & "?script=Testaccess&param=" + lat +"|"+ long;
window.location = theURL;
// alert(theURL) here gives me blank map
}); // END drag-end
map.addAnnotation(marker);
var lat = marker.coordinate.latitude;
var long = marker.coordinate.longitude;
var borchbio = new mapkit.CoordinateRegion(
new mapkit.Coordinate(lat,long),
new mapkit.CoordinateSpan(0.002, 0.002)
);
map.region = mymap;
map.mapType = "hybrid";map.setCenterAnimated(new mapkit.Coordinate(x,y), true);
The solution was to set "fmurlscript" rights. Thanks to #michael.hor257k and more detailed help from #paul_tuckey at the Claris Community. His answer here.
File-->Manage-->Security-->Advanced Settings-->Extended Privileges,
Select fmurlscript
Click Edit,
Add the Privilege set that is aligned to your Account Name to the selected fmurlscript
With this code I am able to run a FM script from javascript. Here is the code that triggers the script. Notice that when my database is "WEBMAP.fmp12" I only use "WEBMAP" as the name. I am sending the lat and long to the script that does stuff with it (converts it and writes to the post). The "fmp18://" targets specific version 18.
var theURL = "fmp18://$/WEBMAP?script=My_FM_Script_Name&param=" + lat +"|"+ long;
window.location = theURL;

How to get Dark Sky API to work using mobile gps

I'm trying to build an app using PhoneGap and although I can get the lat and long from my current position using my mobile phone gps, I can't seem to get weather info out of my dark sky api. I don't know what I am doing wrong.
I've tried to use a json script to get the variables lat and long to plug into my api request. There is something I am missing that is needed to bridge the gap.
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'Altitude: ' + position.coords.altitude + '<br />';
var lat = position.coords.latitude;
var long = position.coords.longitude;
getWeatherData(lat, long)}
}
function getWeatherData(lat, long){
var apiKey = "<my API key>";
var exclude = "?exclude=minutely,hourly,daily,alerts,flags";
var unit = "?units=si";
var url = "https://api.darksky.net/forecast/" + apiKey + "/" + lat + "," + long + exclude + unit;
//get darksky api data
$.ajax({
url: url,
dataType: "jsonp",
success: function (weatherData) {
//weather description
var description = weatherData.currently.summary;
$('#weather-description').text(weatherData.currently.summary);
}
});
print(getWeatherData)
}
function print(getWeatherData){
var element = document.getElementById('weather-description');
element.innerHTML = 'Description ' + weatherData.currently.summary + '<br />';
}
</script>
Then in my HTML...
<p id="geolocation">Finding geolocation...</p>
<p id="weather-description">Loading Description...</p>
Actual results, lat and long and altitude are displayed instead of Finding geolocation, but I expected the weather description to be printed where it says Loading description but it is not.
I worked. Thank you to NewToJS for helping me. The problem was I wasn't calling the function. I've been working on this for 4 days I can't believe it works!

Wunderground Geolocation using $.ajax not appending to HTML

I am experimenting using in using $.ajax to use geolocation to input weather data into a page from Wunderground. I am able to successfully input weather data into my page when I manually enter my location into code using plain vanilla JS but want to take it a step further. I am running the following code and get an alert box asking for location but after clicking okay see no code updates to my HTML. When opening the console in dev tools I do not see any error messages.
var Geo={};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successGeo,error);
}
else {
alert('Geolocation is not supported');
}
function error() {
alert("Cant find you");
}
function successGeo(position) {
Geo.lat = position.coords.latitude;
Geo.lng = position.coords.longitude;
}
function showPosition(position) {
var geoLat = position.coords.latitude;
var geoLong = position.coords.longitude;
var key = "8704dded63fc077d";
var ForecastURL = "http://api.wunderground.com/api/"; + key + "/forecast/q/" + geoLat + "," + geoLong + ".json";
var WeatherURL = "http://api.wunderground.com/api/"; + key + "/conditions/q/" + geoLat + "," + geoLong + ".json";
$.ajax({
url : WeatherURL,
dataType : "jsonp",
success : function(parsed_json) {
var temp_f = parsed_json['current_observation']['temp_f'];
document.getElementById("currentTemp").innerHTML = temp_f;
}
});
$.ajax({
url : ForecastURL,
dataType : "jsonp",
success : function(parsed_json) {
var fore_high = parsed_json['forecast']['simpleforecast']['forecastday'][0]['high']['fahrenheit'];
var fore_low = parsed_json['forecast']['simpleforecast']['forecastday'][0]['low']['fahrenheit'];
document.getElementById("high1").innerHTML = fore_high;
document.getElementById("low1").innerHTML = fore_low;
}
});
} //ends showposition function
I have some div elements set up in the footer of index.html just so I can confirm the elements are being updated. I'll worry more about style and alignment later.
<footer> <!--//contains ajax weather data-->
<div id="high1"></div>
<div id="current_temp"></div>
<div id="low1"></div>
</footer>
I'm pretty stumped as to why I can't get a response, especially since I'm not picking up any errors in the console.

Undefined variable when passing javascript variable to PHP with AJAX

I am trying to build a simple mobile app that checks database and gives user the correct venue based on their location. Essentially, I have two files: one with geolocation, JavaScript and AJAX call, and another one with php that checks the database and sends the correct result back. Everything on its own is working perfectly fine, but when I try to send geolocation coordinates to PHP it returns undefined. Why does it not pick up the coordinates (they pop up in a separate window)? How can I fix it?
Here is my geolocation and AJAX code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$( document ).ready(function() {
var latitude;
var longitude;
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) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
var request = $.ajax({
url: "http://cs11ks.icsnewmedia.net/mobilemedia/ajax.php?latitude=" + latitude + "&longitude=" + longitude,
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#ajax").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
</script>
And here is the bit of PHP that handles these variables:
if (isset($_GET['latitude']) && isset($_GET['longitude'])) {
$latitude = $_GET['latitude'];
$longitude = $_GET['longitude'];
echo "Geolocation seems to work...";
echo $latitude;
echo $longitude;
//continue here
}else{
echo "Hello. I am your geolocation and I am not working.";
}
What I get is "Geolocation seems to work...undefinedundefined"
The Geolocation API is asynchronous, so you have to wait for the result to return
function displayPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
url : "http://cs11ks.icsnewmedia.net/mobilemedia/ajax.php",
data : {latitude : latitude, longitude : longitude},
type : "GET",
dataType : "html"
}).done(function(msg) {
$("#ajax").html(msg);
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
function displayPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}
remove var in both variable. Those two are not visible outside displayPosition. When you use the $.ajax call you're using latitude and longitude declared right under the $(document).raedy() but you never assign nothing to them so they're undefined.
Hope this solve your issue.
P.S. You se the values in the alert because you're using ones from position, not from your variables.
Do not use var inside your displayPosition function. You do not want to declare new variables inside the scope of the function, you want to assign values to the existing variables you declared in the global scope earlier.

Js file for find location / Address?

I need address in project. I am getting address by using Latitude and longitude with including below scripting code.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>
Is there any respective .js file is there to find location instead of loading above URL ?
Please give some suggestions because with out internet connection my app is not loading, It is throwing Application Error.
Click here for your query. I think it will be usefull for you.
why dont you use a function() to get the location and dispaly it within the div??
chk out below:
function Location() {
var latlng = userLatValue + ',' + userLngValue;
var locationUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng="
+ latlng + "&sensor=false";
var locationRequest = $.ajax({
type : 'GET',
url : locationUrl,
async : false,
data : "json"
});
locationRequest.done(function(data) {
if(data.results.length > 0) {
userLocationName = data.results[0].formatted_address;
//alert('address: ' + userLocationName);
}
});
locationRequest.fail(function(jqXHR, textstatus, error) {
//alert("error:");});
}

Categories