This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I'm working on how to push the value of a variable outside a json function. I'm integrating Google maps and Instagram's API together so I'm passing the longitude and latitude coordinates to glat and glng to var url (which is outside the google function. Currently I'm using PHP and not really familiar with json.
var glat;
var glng;
//Google maps latitude and coordinates
$.getJSON(mapurl, function(google){
glat = google.results[0].geometry.location.lat;
glng = google.results[0].geometry.location.lng;
console.log('<?php echo urlencode($_GET['location']);?>');
console.log(glat);
console.log(glng);
//return glat;
});
var url = "https://api.instagram.com/v1/media/search?lat=" + glat + "&lng=" + glng + "&distance=1000&client_id=<?php echo $client_id; ?>&count=40&callback=?";
//This pulls the instagram images
console.log(url);
//Instagram Feed
$.getJSON(url, function (response) {
//http://techmonks.net/instagram-using-the-api/
for(var i = 0; i < 40; i++){
$("#feed ul").append("<li><a target='_blank' href='"+response.data[i].link +"'><img src='"+response.data[i].images.low_resolution.url+"'/></a></li>");
}
});
$.getJSON causes an asynchronous XMLHttpRequest. Since this is asynchronous, lat and lng are not defined when you try to define your URL to point to Instagram.
var glat;
var glng;
//Google maps latitude and coordinates
$.getJSON(mapurl, function(google){
glat = google.results[0].geometry.location.lat;
glng = google.results[0].geometry.location.lng;
console.log('<?php echo urlencode($_GET['location']);?>');
console.log(glat);
console.log(glng);
var url = "https://api.instagram.com/v1/media/search?lat=" + glat + "&lng=" + glng + "&distance=1000&client_id=<?php echo $client_id; ?>&count=40&callback=?";
console.log(url);
$.getJSON(url, function (response) {
//http://techmonks.net/instagram-using-the-api/
for(var i = 0; i < 40; i++){
$("#feed ul").append("<li><a target='_blank' href='"+response.data[i].link +"'><img src='"+response.data[i].images.low_resolution.url+"'/></a></li>");
}
});
});
Related
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!
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 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];
}
?>
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:");});
}
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>