The simplest (or at least the one functional) way to init JSON obejct from URL (Geocoding API)

StackOverflow https://stackoverflow.com/questions/10372846

Domanda

Im trying to geocode in my javascript code against Geocoding API. I get url defined var url = "http://http://maps.googleapis.com/maps/api/geocode/json?address=New York, Manhattan&sensor=false" from which I need to retrive a JSON object. First approach I used was according to Wikipedia using XmlHttpRequest like this

var my_JSON_object = {};
var http_request = new XMLHttpRequest();
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
  var done = 4, ok = 200;
  if (http_request.readyState == done && http_request.status == ok) {
       my_JSON_object = JSON.parse(http_request.responseText);
  }
};

I run the code and get such output in debugger after open() function was triggered:

http_request: XMLHttpRequest
onabort: null
onerror: null
onload: null
onloadend: null
onloadstart: null
onprogress: null
onreadystatechange: function () {
readyState: 1
response: ""
responseText: ""
responseType: ""
responseXML: null
status: [Exception: DOMException]
statusText: [Exception: DOMException]
upload: XMLHttpRequestUpload
withCredentials: false
__proto__: XMLHttpRequest

which means that nothing really useful obviously happened. My second approach was due to json.org, Ive tried to make a get call with JSONRequest

var requestNumber = JSONRequest.get(
url, 
function (requestNumber, value, exception) {
    if (value) {
        document.write(value);
    } else {
        document.write(exception);
    }
}

Debugger told me that JSONRequest is not defined! Due to json.org its native JS object so whats the problem? Just to notice, i use properly gained API key from google in the script nearby.

Explanation why my solution failed and any suggestion how to comply with this task would be much appreciated!

È stato utile?

Soluzione

I read about hacks like cross domain XHR and Apache/HTTP proxies but the conclusion is that the Javascript API V3 geocoding is your only realistic option. This comment, (from here) while not authoritative, shows that such JSON requests don't work anymore:

One would reasonably expect the google maps api to allow cross domain access, which it did until recently. Now it doesn't allow it any more; i guess they allege security reasons but I also guess the real reason is to oblige you to use only their code to get their service. So the only way to get the data via javascript from the client is to use Google's javascript api, which anyway gives you almost the same flexibility as calling the api url directly.

This question had the most useful information.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top