1

I'm using JQuery to try to read JSON and I keep ending up in the error handler. When I inspect the DOM all I see is "error" under statusText with no more details. I've tried saving this to a local file and have added the beforeSend section to address potential MIME problems based on another post. When I open the url in a browser it does generate valid JSON.

$.ajax({
type : "GET",
url : "http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true",
beforeSend : function(x) {
    if (x && x.overrideMimeType) {x.overrideMimeType("application/j-son;charset=UTF-8");}},
dataType : "application/json",
success : function(data) {
    alert("success" + data)},
error : function(y) {alert("failure" + y.statusText);}

});

user743183
  • 221
  • 2
  • 3
  • 6

1 Answers1

3

There is nothing wrong with your code. The problem is occurring because you are trying to perform a cross-domain AJAX request. However, not all is lost because Google provides their Google Maps Javascript API V3 Services - a client-side Geocoding API.

The following full code sample (tested and working) will give you access to the JSON object that you require. In this example, an alert box will display "Williamsburg, NY, USA" - the first formatted_address.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript">
$(document).ready(function() {
    var geocoder = new google.maps.Geocoder();
    var input = "40.714224,-73.961452";
    var latlngStr = input.split(",", 2);
    var lat = parseFloat(latlngStr[0]);
    var lng = parseFloat(latlngStr[1]);
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                alert(results[1].formatted_address);
            }
        } else {
            alert("Geocoder failed due to: " + status);
        }
    });
});
</script>
NakedBrunch
  • 48,713
  • 13
  • 73
  • 98
  • @user743183: This is your 9th question and you have yet to accept a single answer. A lot of people contribute to your questions and you should take a moment to accept those answers that helped you. Not every answer is exactly what you're looking for but, for this question, you are getting exactly what you need. It's time for you to give some love back to the StackOverflow community or people won't be inclined to help you in the future. I urge you to learn more about upvoting and marking questions as answered. Go to this link to read more: http://meta.stackexchange.com/q/5234/148310 – NakedBrunch Jul 10 '11 at 03:03