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!
Related
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.
I am trying to run a Javascript code to retrieve a device's geolocation. When I try to run the code from the localhost (127.0.0.1) the code runs as expected, opening a pop up to ask the user to enable location services. However, when I try to host this code or access it using the local IP address (192.168.x.y), the code fails with an error
Any ideas as to why it works for localhost and not otherwise.
Here's the JS Code
function geoFindMe() {
var output = document.getElementById("out");
if (!navigator.geolocation){
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
output.appendChild(img);
}
function error() {
output.innerHTML = "Unable to retrieve your location";
}
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, error);
}
Thanks.
Recent versions of Chrome require secure protocols for some features. Fore example a page must be served up httpS for it to be able to obtain the user's geolocation.
The restriction is relaxed for localhost to enable dev/debugging.
I refer to the question Polygon "Drawing and Getting Coordinates with Google Map API v3" and the code by jhawes which works fine; BUT I've struggle to post the lat/lng-values to a DB using php.
In other scripts with single coordinates I use the following (whereas the variables "BlattNr, Quadrant, MTBlat, MTBlng, Qmlat, Qmlng" are of no interest for that question):
function saveData(BlattNr, Quadrant, MTBlat, MTBlng, Qmlat, Qmlng) {
var latlng = marker.getPosition();
window.location.href = "schritt_2.php?lat=" + latlng.lat() +
"&lng=" + latlng.lng() + "&MTBNr=" + BlattNr + "&Quadrant=" + Quadrant + "&MTBlat=" + MTBlat + "&MTBlng=" + MTBlng + "&Qmlat=" + Qmlat + "&Qmlng=" + Qmlng;
marker.setMap(null);
}
With this I can post the lat and lng of the single point coordinate - but how to pass the multiple lat and lng of various points? I don't know how to define the variable and how to construct the "saveData" function...
Many thanks in advance for any help :-)
Okay, I copy/pasted the code that jhawes put in jsFiddle
I added a few things.
add jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Save_data
function save_data() {
var data = [];
var len = myPolygon.getPath().getLength();
for (var i = 0; i < len; i++) {
data.push([myPolygon.getPath().getAt(i).lat(), myPolygon.getPath().getAt(i).lng()]);
}
// send data to the server
$.ajax({
url: 'save.php?p=' + JSON.stringify(data),
success: function (message) {
$('#ajaxresponse').html(message);
}
});
}
A button and a display div. Put them somewhere at the bottom of the markup.
<input type="button" onclick="save_data()" value="SAVE">
<div id="ajaxresponse"></div>
Server side: I don't do much here; I'm sure you can handle it.
save.php
<?php
if (isset($_GET['p'])) {
$locations = json_decode($_GET['p'], true);
echo print_r($locations, true) . '<br>';
echo "let's print the second point: lat=" . $locations[1][0] . ", lng=" . $locations[1][0];
}
?>
What I am trying to do:
Get location based off of IP (Done)
Use the City and Country code to use openweather's API (Done)
Read the XML into my webpage so that I can display the "Temperature" field.
This is my first venture into using XML in webpages, and I've tried for 3 days now with no success. I have searched google and stackoverflow, and have tried many things so far, including SimpleXMLElement, with no luck.
What I currently have on my page is just a generated link to the XML sheet for your location.
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript">
var country = geoip_country_code();
var city = geoip_city();
document.write('Link text');
</script>
How am I able to display the text from the required field on my page?
Thanks in advance! :)
It might be easier to change the API call to return JSON, in which case you could then use this code, the temps are stored in temp, temp_min and temp_max.
var country = geoip_country_code();
var city = geoip_city();
$.getJSON('http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=json&units=metric', function( json ) {
var temp = json.main.temp;
var temp_min = json.main.temp_min;
var temp_max = json.main.temp_max;
document.write( 'Temp: ' + temp + '<br>');
document.write( 'Temp Min: ' + temp_min + '<br>');
document.write( 'Temp Max: ' + temp_max + '<br>');
});
You could use javascript library to convert the xml into a javascript object - one such library is called xml2json, it works as a jQuery plugin: http://www.fyneworks.com/jquery/xml-to-json/
Then you can simply do:
var xmlObject;
$.ajax({
url: url_of_xml,
success: function(data) {
xmlObject = $.xml2json(data);
}
});
Then you just need to place the data on your page. The object in my example is faked, but it gives you the idea:
// put this line in the success callback of your ajax call
// after you create the xmlObject
$('#temp').html(xmlObject.weather.temp);
To display the temperature you get the XML, and read one of the three temperature attributes from the XML returned:
$.get("http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=xml&units=metric", function(xml) {
avg = $(xml).find("temperature").attr("value"));
max = $(xml).find("temperature").attr("max"));
min = $(xml).find("temperature").attr("min"));
(using JQuery)
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>