Retrieving JSON throws error: Unexpected token : - javascript

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);
}

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!

How to get temperature value on javascript (serverside)?

I was looking to use a weather API (like yahoo's) and make my javascript code able to return the temperature given a city.
My app runs on rivescript (built on javascript and node).
Researching I only found ways to do it locally on json, or by using html and css as well, but I just want a simple javascript code that returns a value with the temperature.
Thanks
You can try something like this, using openweathermap.org APIs:
function getWeather(city, callback) {
var url = 'http://api.openweathermap.org/data/2.5/weather';
$.ajax({
dataType: "jsonp",
url: url,
jsonCallback: 'jsonp',
data: { q: city },
cache: false,
success: function (data) {
callback(data.main.temp);
}
});
}
This example uses a name of a city as input, and returns temperature in K° degrees.
The data.main.temp value is returned, but you could return just data to have the whole weather object for that city.
Otherwise, if you want to use Yahoo Weather API (with your APPID):
function getWeather(position, callback) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
// Yahoo's PlaceFinder API http://developer.yahoo.com/geo/placefinder/
// We are passing the R gflag for reverse geocoding (coordinates to place name)
var geoAPI = 'http://where.yahooapis.com/geocode?location='+lat+','+lon+'&flags=J&gflags=R&appid='+APPID;
// Forming the query for Yahoo's weather forecasting API with YQL
// http://developer.yahoo.com/weather/
var wsql = 'select * from weather.forecast where woeid=WID and u="'+DEG+'"',
weatherYQL = 'http://query.yahooapis.com/v1/public/yql?q='+encodeURIComponent(wsql)+'&format=json&callback=?', code, city, results, woeid;
// Issue a cross-domain AJAX request (CORS) to the GEO service (not supported in Opera and IE)
$.getJSON(geoAPI, function(r) {
if (r.ResultSet.Found == 1) {
results = r.ResultSet.Results;
city = results[0].city;
code = results[0].statecode || results[0].countrycode;
woeid = results[0].woeid; // the the city identifier for the weather API
// Make a weather API request (it is JSONP, so CORS is not an issue):
$.getJSON(weatherYQL.replace('WID', woeid), function(r) {
if (r.query.count == 1) {
var item = r.query.results.channel.item.condition;
callback(item.temp
} else {
console.error("Error retrieving weather data!");
}
});
}
}).error(function(){
console.error("Sorry, your browser does not support CORS requests!");
});
}
This example uses a position as input (see navigator.geolocation), and returns temperature in C° degrees.
Note:
- both examples imply the use of jQuery.
- the second example implies having obtained a Yahoo APPID

How do I access a certain string variable in a json API?

I am using the weatherunderground api, and I would like to access the forecast only for today. I usually use parsed_json[][] until I get the variable I need, but in this case there is an array. Here is my code:
function findWeather() {
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/c531e176f43b999d/forecast/q/CT/Old_Greenwich.json",
dataType : "jsonp",
success : function(parsed_json) {
var forecasts = parsed_json['forecast']['txt_forecast']['forecastday: 0']['fcttext'];
var forecastString = "The weather is" + forecasts + "."
speak(" test" + forecastString);
}
});
});
}
function speak(x) {
var msg = new SpeechSynthesisUtterance(x);
window.speechSynthesis.speak(msg);
}
If you go to the URL, you will see the entire sheet and the info I am trying to access. I've been trying to solve this for a few hours, and can't find any help with google.
Try this:
parsed_json['forecast']['txt_forecast']['forecastday'][0]['fcttext'];
Don't know what you expect the :0 to do, but it won't de-reference the array.

Extracting data from JSON with ASP.Net web service

I am trying unsuccessfully to extract the formatted_address property.
The following web service logs the JSON below to the console. I cannot get the formatted address using returnedData.d.results[0].formatted_address.
$.ajax({
type: "POST",
url: "ReportIncident.aspx/ReverseGeocode",
data: "{latitude:" + latitude + ",longitude:" + longitude + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (returnedData)
{
console.log(returnedData);
}
});
The format of the json is the exact same as the format over here at Google.
Edit
Darin pointed out that I was contradicting myself: the web service wraps up everything in the link above in a d object, I failed to mention that.
Further edit
Here is the web service:
[WebMethod]
public static string ReverseGeocode(decimal latitude, decimal longitude)
{
// Create the web request
string url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude +"&sensor=true";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
and here is the javascript:
/Gets the current location of the user
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position)
{
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
type: "POST",
url: "ReportIncident.aspx/ReverseGeocode",
data: "{latitude:" + latitude + ",longitude:" + longitude + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (returnedData)
{
alert(returnedData.d[0].results[0].formatted_address);
console.log(returnedData);
}
});
Have you tried using returnedData.results[0].formatted_address without the .d. node. That does not exist!
remove the ".d"
returnedData.results[0].formatted_address
but doing this you are always getting the first node only
The answer to this issue turns out to be that the web service is returning a string, instead of json. The built-in javascript serializer does not get used. The eval keyword or something more secure needs to be used. As it happens I ended up using the Google Maps Javascript API and that was much easier anyway.

Problem with connecting to google map url to fetch lattitude and longitude for particular location

I have the following code to fetch lattitude and longitude for given address but the permission to google url is denied .
function getlatlng(address, callback) {
var addressval = address;
var address;
var url;
var googleUrl = "http://maps.google.com/maps/api/geocode/json?";
var sensor = "&sensor=false";
if (addressval != null && addressval != "" && addressval.length != 0) {
address = "address=" + encodeURIComponent(addressval);
$.ajax({
url: googleUrl + address + sensor,
type: "POST",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(longlatJson) {
var jsonObj = JSON.parse(JSON.stringify(longlatJson));
var lat = jsonObj.results[0].geometry.location.lat;
var lng = jsonObj.results[0].geometry.location.lng;
cb(lat, lng);
},
error: function() { alert("unable to conect to google server"); }
});
}
}
This will be my function call to getlatlng for the given address
getlatlng(address, function(lat, lng) {
alert(lat);
alert(lng);
...............
...............
});
You don't need a key for v3.
The problem is that the Google Maps JSON web service does not use jsonp so you can't use it how you are becuase you are hitting the cross domain policy of browsers.
You either need to have your server do that request (via wget or something) and then pass the results back to the browser or instead use the Google Maps API geocoder and that will handle it for you.
You can read more here http://code.google.com/apis/maps/documentation/javascript/services.html#Geocoding
I don't see any reference to an API key in your code; do you send it with your requests ?

Categories