0

I have a problem with google API url. I want to get the address from a zipcode. But i can't get the value

My code is

<script type="text/javascript">
var filter_new = "60609";
var request = new XMLHttpRequest();
        request.open("GET", "http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address="+filter_new, false);
        request.send();
        var xml = request.responseXML;
        var users = xml.getElementsByTagName("GeocodeResponse");
        for(var i = 0; i < users.length; i++)
        {
            var user = users[i];
            var names = user.getElementsByTagName("formatted_address");
            for(var j = 0; j < names.length; j++)
            {
                var filter_new1=names[j].childNodes[0].nodeValue;
            }
        }
alert(filter_new1);
</script>

When i run this code it shows the following errors:

XMLHttpRequest cannot load http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address=60609. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101 

Please help me.

Preethy
  • 722
  • 2
  • 10
  • 27

2 Answers2

0

You can initate CORS or JSONP request. Google supports both. Please study them at

  1. JSONP: http://api.jquery.com/jQuery.getJSON/ http://learn.jquery.com/ajax/working-with-jsonp/

  2. CORS: How to get a cross-origin resource sharing (CORS) post request working http://www.html5rocks.com/en/tutorials/cors/

Community
  • 1
  • 1
Anand Shah
  • 611
  • 7
  • 14
0

You have multiple issues with your code:

  1. Browsers don't generally allow you to do direct Ajax to domains that are different than the page you're on. This is called same-origin protections. This is the error you are seeing. The typical way you work around this is by doing a JSONP call which uses a script tag to work around this limitation. You can read about how to do that on Google's API site.

  2. You're using async false as an argument (e.g. trying to do a synchronous ajax call). Since you are probably going to use JSONP which can only be asynchronous, you will need to change the way your code works to work with an asynchronous response. Here's a Google Maps API example of JSONP.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • i used JSONP but it does not working.An error is showing : Resource interpreted as Script but transferred with MIME type application/xml – Preethy Nov 05 '13 at 07:18
  • @Preethy - You need to change the URL to request JSON, not XML. – jfriend00 Nov 05 '13 at 07:21