Fetch 10000 coordinates synchronously using Google Maps - javascript

I want to fetch coordinates of 10,000 line of data using Google Maps geocoding API, and print each line to browser.
My approach is to loop each line (contain address) and pass it to Google Maps URL, then I parse those JSON data to get its lat and lng. I use jQuery.
But the problem here is it seems to run asynchronously. I have tried to use recursive but it loop without print anything. I have read to set async=false but I dont know where to place it.
Here is my current code
var x = 1;
setInterval(function(){
geturl = 'parse.php?urut='+x;
$.get(geturl, function(get){
url = get;
});
$.getJSON(url, function(data){
var lat = data.results[0].geometry.location.lat;
var lang = data.results[0].geometry.location.lng;
var nama = data.results[0].address_components[1].long_name;
$('table').append("<tr><td>"+x+"</td><td>"+lat+","+lang+"</td><td>"+nama+"</td></tr>");
});
x++;
}, 500);
Any recommendation?

This snippet of code should show you where you went wrong
function getCoords(x) {
geturl = 'parse.php?urut='+x;
$.get(geturl, function(url){
$.getJSON(url, function(data){
var lat = data.results[0].geometry.location.lat;
var lang = data.results[0].geometry.location.lng;
var nama = data.results[0].address_components[1].long_name;
$('table').append("<tr><td>"+x+"</td><td>"+lat+","+lang+"</td><td>"+nama+"</td></tr>");
});
});
}
the $.getJSON is run as part of the success function of the $.get - therefore it will get run only once the $.get is complete
I've shown this as a function, so that the value of x will be correct in the $('table').append line

Related

How to get JSON after geolocation in JavaScript/jQuery?

I'm building a project that finds the geolocation from the browser, then uses the coordinates to get data from the Dark Sky API (https://darksky.net/dev/).
I am able to get the geolocation from the browser, but am having trouble calling the JSON object once I get the geolocation. I understand that getting the geolocation is "asynchronous" and runs at the same time as my other code, and I can't seem to figure out a way around it.
Am I'm doing something wrong? It never seems to runs the: $.getJSON part.
All the #test htmls are for my reference to see where my code is going wrong. #test4 never runs, but #test3 does.
P.S. I've kept the API key hidden for my question, hence the KEY characters in the url. The myJson variable does concatenate a proper url to retrieve the JSON object.
Any help would be deeply appreciated!
var myLat;
var newMyLat;
var myLong;
var newMyLong;
var myJson;
var functionCall;
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
myLat = position.coords.latitude;
myLong = position.coords.longitude;
newMyLat = parseFloat(myLat).toFixed(4);
newMyLong = parseFloat(myLong).toFixed(4);
$("#test1").html("latitude: " + newMyLat + "<br>longitude: " + newMyLong);
myJson =
"https://api.darksky.net/forecast/KEY/" +
newMyLat +
"," +
newMyLong;
$("#test2").html(myJson);
getJsonData();
}); // end of getCurrentPosition function
} // end of navigator.geolocation function
}); // end of document.ready function
function getJsonData() {
$("#test3").html("getJsonData called");
$.getJSON(myJson, function(data) {
$("#test4").html("JSON retrieved");
}); // end of .getJSON function
} // end of getJsonData function
Answer that worked for this situation:
I just needed to add ?callback=? to the end of my JSON url, making it:
myJson = "https://api.darksky.net/forecast/ee2f66f091ed810afc3bf04adc5fa750/" + myLat + "," + myLong + "?callback=?";
Thank you for all the help!

Very simple API call that doesn't return anything

I'm trying to get data from the open weather API but all I get is an object that I cannot use (the JSON is inside but I cannot access it)
I've read a lot about asynchronous JS and callbacks. I'm really not sure whether I need a callback for EACH API i'm using, I already used one to get latitude and longitude but now, for the open weather API, i need to pass these lat and lon as parameters for the API call, and I have no idea on how to do that if I use callbacks (as it seems that arguments in callbacks functions are not the ones used in the function but the ones that actually get returned, which I find extremely confusing).
Can anyone tell me what I'm doing wrong here?
$(document).ready(function() {
$('#getWeather').on('click', function(){
myLatAndLon(function(result) {
var lat = result[0];
var lon = result[1];
console.log(myWeather(lat, lon));
// Here, although the params work in browser, the message that gets returned in console is : "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied"
});
})
})
function myLatAndLon(callback) {
$.getJSON('http://ip-api.com/json/').done( function(location) {
var arr = [];
arr.push(location.lat);
arr.push(location.lon);
callback(arr);
});
}
function myWeather(lat, lon) {
return $.getJSON('http://api.openweathermap.org/data/2.5/weather', {
lat: lat,
lon: lon,
APPID: 'a9c241803382387694efa243346ec4d7'
})
// The params are good, and when I type them on my browser, everything works fine
}
Change your code to it and test again :
$(document).ready(function() {
$('#get').on('click', function() {
myLatAndLon(function(result) {
var lat = result[0];
var lon = result[1];
alert(JSON.stringify(result));
$req = myWeather(lat, lon);
$req.done(function(R) {
alert(JSON.stringify(R))
});
});
})
})
function myLatAndLon(callback) {
$.getJSON('//ip-api.com/json/').done(function(location) {
var arr = [];
arr.push(location.lat);
arr.push(location.lon);
callback(arr);
});
}
function myWeather(lat, lon) {
return $.getJSON('//api.openweathermap.org/data/2.5/weather', {
lat: lat,
lon: lon,
APPID: 'a9c241803382387694efa243346ec4d7'
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="get">get</button>
And also you should check your server for CORS limitations read more here:
http://enable-cors.org/server.html

show local weather using openweathermap api

I am going to make a web app that show local weather using openweathermap api.
When I click the button, an IP API was called to get the co-ordinate of my location(longitude and latitude). These information then was used with API key (I registered in the website openweathermap.org) to create URL to call weather info according to the APIdocs, then change the HTML element with the data got from the server. I doing this on codepen. I tried to do the simplest one but it doesn't work.
<h1>weather forcast</h1>
<button id="btn">view</button>
<p id ="test">change me</p>
<p id ="place">place</p>
<p id ="temp">temperature</p>
<p id ="description">description</p>
var getLocation = function(data) {
var lat = data.lat;
var lon = data.lon;
var apiKey = "[APIKEY]";
};
var url = 'http://api.openweathermap.org/data/2.5/weather?' + 'lat=' + lat + '&lon=' + lon + '&appid=' + apiKey;
//call back function to extract weather info.
var getWeather = function(data) {
var temp = data.main.temp;
var description = data.weather[0].description;
var place = data.name;
};
$(document).ready(function() {
$("#btn").click(function() {
$.getJSON('http://ip-api.com/json', getLocation, 'jsonp')
$.getJSON(url, getWeather, 'jsonp');
$("#test").text("I AM CHANGED. THANKS!")
$("#temp").text(temp)
$("#description").text(description)
$("#place").text(place)
})
})
You have several issues. The first is that the $.getJSON calls are asynchronous, so the text() of the elements will be changed before any request completes. You need to place all code dependant on the values returned from the request in the callback functions.
Secondly you have issues with variable scope where you're defining your variables inside the function and then attempting to use them outside where they will be undefined.
With that said, you need to re-arrange your logic to something like this:
var getWeather = function(data) {
$.getJSON('http://api.openweathermap.org/data/2.5/weather', {
lat: data.lat,
lon: data.lon,
appid: "[APIKEY HERE]"
}, showWeather, 'jsonp');
};
var showWeather = function(data) {
$("#test").text("I AM CHANGED. THANKS!")
$("#temp").text(data.main.temp)
$("#description").text(data.weather[0].description)
$("#place").text(data.name)
};
$(document).ready(function() {
$("#btn").click(function() {
$.getJSON('http://ip-api.com/json', getWeather)
})
})
Note that the function calls are chained from the event (ie the click makes the location AJAX request, which calls getWeather which then calls showWeather. Also note how the variables are now local and used within their own function scope.
Finally, check that you're using the correct data formats for the AJAX requests. ip-api.com/json is returning JSON, not JSONP.
You can get data about the location with use third-party API. for example:http://ip-api.com/.
You get your location weather data from OpenWeatherMap service using the ip-api. its help you to get visitor location weather.
var getIP = 'http://ip-api.com/json/';
var openWeatherMap = 'http://api.openweathermap.org/data/2.5/weather'
$.getJSON(getIP).done(function(location) {
$.getJSON(openWeatherMap, {
lat: location.lat,
lon: location.lon,
units: 'metric',
APPID: 'Your-Openweather-Apikey'
}).done(function(weather) {
$('#weather').append(weather.main.temp);
console.log(weather);
})
})

How can i get latitude and longitude coordinates from JSON Google Maps

I know what i can get JSON LatLon (and other) data indicate my address in the URL
app.factory('myCoordinates', function myCoordinates($q, $http) {
var deferred = $q.defer();
$http.get('http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region')
.success(function(coordinates) {
var myCoordinates = {};
myCoordinates.lat = coordinates.results[0].geometry.location.lat;
myCoordinates.lng = coordinates.results[0].geometry.location.lng;
myCoordinates.zoom = 14;
deferred.resolve(myCoordinates);
})
return deferred.promise;
});
http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region
But how can i get latitude and longitude coordinates of my current location without input my address in URL (automatically) ?
How about using html5 navigator.geolocation.getCurrentPosition to get the latitude and longitude?
Example:
navigator.geolocation.getCurrentPosition(function(pos){
console.log(pos)
});

Retrieving JSON throws error: Unexpected token :

I'm retrieving the elevation data from the Google Maps API by AJAX.
I'm getting the data back I want as if I look at the console in Chrome I can see a 200 status code and can see the data in the response tab. But is throws up 'Uncaught SyntaxError: Unexpected token :' so I can't display anything from the JSON file.
This is my code:
var theURL = 'http://maps.googleapis.com/maps/api/elevation/json?locations=' + longitude + ',' + latitude + '&sensor=false&callback=?';
$.ajax({
url: theURL,
type: 'get',
dataType: 'json',
cache: false,
crossDomain: true,
success: function (data) {
var theData = $.parseJSON(data);
console.log(theData);
}
});
The live code is here: http://map.colouringcode.com/
All help is greatly appreciated.
The Google Maps API does not support direct JSONP requests.
Instead, you need to use the Javascript API.
Realizing this question is well outdated, I hope that this might be able to help someone in the future. This was my first encounter with javascript and especially all this JSON stuff and therefore caused a lot of hitting my head off the desk trying to figure out what I was doing wrong.
Here is my solution that retrieves the clients location (in lat and lng) and then uses the google geocoding api to determine their location in "human readable" format.
function currentLocation() {
navigator.geolocation.getCurrentPosition(foundLocation, errorLocation);
function foundLocation(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//This is where the geocoding starts
var locationURL= "http://maps.googleapis.com/maps/api/geocode/json?latlng="
+ lat + "," + lng + "&sensor=false&callback=myLocation"
//This line allows us to get the return object in a JSON
//instead of a JSONP object and therefore solving our problem
$.getJSON(locationURL, myLocation);
}
function errorLocation() {
alert("Error finding your location.");
}
}
function myLocation(locationReturned) {
var town = locationReturned.results[0].address_components[1].short_name;
var state = locationReturned.results[0].address_components[4].short_name;
console.log(town, state);
}

Categories