views:

140

answers:

2

using http://maps.google.com/maps/api/geocode/json?address=xyz we get a json file I am wondering how can i maniupluate the results in javascript? How do i create the results object in javascript?

http://code.google.com/apis/maps/documentation/geocoding/index.html#JSONParsing this doesnt really explain how they get the myJSONResult

+1  A: 

You can use eval to parse the JSON into a JavaScript object, but this isn't recommended for security reasons. Use a JSON parser to turn the JSON string into a JavaScript object that you can manipulate.

Using eval:

myJSONResult = eval("{}");

Using the above linked parser:

myJSONResult = JSON.parse("{}");
Bob
+1  A: 

The way you get the JSON is using an AJAX retrieval. This can be accomplished using hand coded JavaScript, but is far far easier using jQuery. Here's a quick example:

            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
            <script type="text/javascript">
            $(document).ready(function() {
                $.ajax({ url: "http://maps.google.com/maps/api/geocode/json",
                         type: "GET",
                         dataType: "json",
                         data: { address: "1600+Amphitheatre+Parkway,+Mountain+View,+CA", sensor: "false" },
                         success: function(data, textStatus, XMLHttpRequest) {
                             console.log(textStatus);
                             alert(data);
                         },
                         error: function(XMLHttpRequest, textStatus, errorThrown) {
                             console.log(textStatus);
                         }});
            });
            </script>

BUT BUT BUT this will NOT work, because of the same origin policy. The way around that is to use a server side language of your choice (Perl, PHP, ColdFusion, ASP) to act as a proxy. That way the url value would be "yourproxy.php", "yourproxy.cfm", "yourproxy.asp" or whatever. That script would simply take the request it receives, act as a user agent to send the request to Google and retrieve the response (aka the URL that is the url value in the code above), and send out the results to your script.

The jQuery library handles the JSON processing for you, or you can use the information provided by Bob along with the hand rolled AJAX listed above. Note that hand rolled AJAX will need the same proxy solution to be able to get information from Google.

Also note that the Geocoding API you linked to is not meant for lots of dynamic queries. They lead you to the API V2 Client Geocoder, the API V3 Client Geocoder, and the Maps API for Flash Client Geocoder.

Tony Miller
the reason i am using the webservices is that the google.com apis are extremly slow in China to load. I can load the map api with google.cn. But for some reason the geocoder apis that load dynamically always uses google.com
hao