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.
Related
My code returns : interne server error
var parameters = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:envelope xmlns:xsi='ttp://www.w3.org/2001/xmlschema-instance' xmlns:xsd='http://www.w3.org/2001/xmlschema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<soap:body>" +
"<listeVille xmlns='http://..../b1'>" +
"<ville>"+ "Test" +"</ville>" +
"</listeVille>" +
"</soap:body>" +
"</soap:envelope>";
$.ajax({
type: "POST",
url: _URL_SITE + "webservices/b1.asmx",
dataType: "xml",
data: parameters,
contentType: "application/soap+xml; charset=utf-8",
headers: {
Accept: '*/*',
SOAPAction: 'http://.../webservices/b1/ListeVille' },
success: function (xml) {
alert('test');
//var _xmldoc
//_xmldoc = new activexobject("microsoft.xmldom");
//_xmldoc.async = "false";
//_xmldoc.loadxml(xml);
},
error: function () {
alert('error');
}
});
And my web service :
<WebMethod(True)> Public Function ListeVille(ByVal ville As String) As System.Xml.XmlDocument
Dim _xml As System.Xml.XmlDocument = New System.Xml.XmlDocument
Dim _hsh As New ParameterCollection
Try
_hsh.Add("#Ville", "")
_xml.LoadXml(_hsh)
Catch ex As Exception
AjoutJournal(ex)
End Try
Return _xml
End Function
I try to call my web service and get a xml file.
For information, don't focus on my function ListeVille, it returns the great value.
Thanks!
You are getting an Internal Server Error which means that there is an Exception in your server Side Code.
If you enable the Remote Errors then you can see the errors on the remote machine. Otherwise, if you debug the code on the machine, you can see the exception Details.
Moreover, the usage of XmlDocument.LoadXml Method doesn't seem to be correct as posted in your question. The Parameter to the LoadXml is a String containing the XML document to load. Try to pass in a valid XML. You can find more details on msdn here
I have been stuck at this problem for almost two days now and I don't seem to find any solution. I have hosted a WCF service on my machine that contains a method SendCredentials which accepts two string parameters.
Now I am supposed to send a public key to my service through which it will do encryption(Asymetric cryptography) and send some information back to the client.
I am not able to pass that public key to the service method from the client as it is in XML format.Here is my client side code:
$(document).ready(function () {
$("#btnSend").click(function () {
debugger;
jQuery.support.cors = true;
var doOaepPadding = true;
var rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
_privateKey = rsa.ToXmlString(true);
_publicKey = rsa.ToXmlString(false);
var data = $("#txtName").val();
var name = "testvalue";
var _privateKey = rsa.ToXmlString(true);
**var _publicKey = rsa.ToXmlString(false);**
//<![CDATA[ and ]]>;
$.ajax({
type: "POST",
url: 'http://localhost:51348/TestService.svc/SendCredentials',
crossDomain: true,
data:JSON.stringify({ mac: "bac", pubKey: _publicKey }),
contentType: "application/json",
dataType: "json",
success: function (result) {
var ans = JSON.stringify(result);
alert(ans);
// result = new XMLSerializer().serializeToString(result.documentElement);
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
return false;
});
});
</script>
_publicKey is the variable I want to pass but throws above said error. Any suggestions How do i pass this XML variable would be really appreciated.
I would suggest you to convert _publicKey to base64 string
convert your _publicKey to string then byte Array and use
Convert.ToBase64String(byte[] inArray)
and on the service side do the reverse
System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(endodedString), true));
i have tried to update,checkout,checkin AND retrive the checkin comment but im getting value does not fall within the range error? anything i have missed ?
var getfileurl = document.getElementById("getfileurl").value;
//i have entered the path like /lib/folder/test.docx
alert(getfileurl);
var executor;
// Initialize the RequestExecutor with the app web URL.
executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: appweburl + "/_api/SP.AppContextSite(#target)/web/GetFileByServerRelativeUrl('" + getfileurl + "')/CheckInComment?#target='" + hostweburl + "'",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: SuccessHandler,
error: ErrorHandler
});
The error:
Value does not fall within the expected range
occurs since serverRelativeUrl parameter for SP.Web.getFileByServerRelativeUrl Method should be specified as server-relative URL for the file, for example:
/_api/web/GetFileByServerRelativeUrl('/site/web/library/filename')
Solution
Specify file url in the following format:
/site/hostweb/library/filename
for example:
var fileurl = _spPageContextInfo.siteServerRelativeUrl + "/documents/filename";
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);
}
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 ?