Mr. Fox
Mr. Fox

Reputation: 328

Call JSON element from an API and return result as string

I'm trying to call an element specifically (country) from an API and I want it to return as string, I'll elaborate it below

USER's INPUT:
New York, NY, United States

API used:
http://maps.google.com/maps/api/js?sensor=true&libraries=places

Desired Result:
United States/US/USA

JSON something not sure what it's called:
https://maps.googleapis.com/maps/api/geocode/json?address=New%20York,%20NY,%20United%20States&sensor=true

I'm a bit lost on how to do it, but this what I tried:

<html>  
<head></head>
<title>Project 9</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&libraries=places"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
     $("#btn1 ").click(function() {
       var address=encodeURI($('#userInput').val());
       var url='https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=true';
       $.getJSON(url, function(data){
          var shortname=data.results[0].address_components[3].short_name;
          var longname=data.results[0].address_components[3].long_name;
          alert(shortname+' '+longname);
     });
   });
});
</script>         
<body>
<input type="text" value="sdfasd" name="userInput" id="userInput" />
  <input type="button" id="btn1" value="Load Data" />
</body>
</html>

I updated the question, I appreciate all of your answers however I noticed that in some inputs, it desn't return the country but returns the object that is in index 3 of the address_components how can we limit it to return only the country? thanks

Could it work like this?

  var shortname=data.results[0].address_components[country].short_name;
  var longname=data.results[0].address_components[country].long_name;
  alert(shortname+' '+longname);

Upvotes: 1

Views: 4222

Answers (5)

Mehran Hatami
Mehran Hatami

Reputation: 12961

firstly, read this article.

The getJSON signature is like:

jQuery.getJSON( url [, data ], callback);

and the callback function signature is like:

callback( data, textStatus, jqXHR );
  • data is the desired json object
  • textStatus is a string to check the status of the ajax request
  • jqXHR is the actual ajax request object

So if you have data to be sent as a query-string, like address as the parameter, you can send it like:

var url = "https://maps.googleapis.com/maps/api/geocode/json"
var data = {
    address: "New York, NY, United States",
    sensor: true
};
jQuery.getJSON(url, data, function(data, status, xhr){
    console.log(data.results);
    for(var i=0;i<data.results.length;i++){
        var result = data.results[i];

        //all addresses as a string
        console.log(result.formatted_address);

        //info about your addresses which is an array
        console.log(result.address_components);

        console.log(result.geometry);
        /*the result.geometry is like:

        bounds: Object
        location: Object
        location_type: "APPROXIMATE"
        viewport: Object
            northeast: Object
                lat: 40.9152555
                lng: -73.700272
            southwest: Object
                lat: 40.496006
                lng: -74.2557349
        */

    }
})

Upvotes: 1

Kaz-LA
Kaz-LA

Reputation: 226

<html>  
<head>
<title>Project 9</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&libraries=places"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
    $("#btn1").click(function (event) {
        // $.getJSON(url,data,success(data,status,xhr))
        var url = 'https://maps.googleapis.com/maps/api/geocode/json?sensor=true';
        var data = { address: 'New York,NY,United States'};
        $.getJSON(url, data, function (result) {
            var components = result.results[0].address_components;
            for (var i = 0; i < components.length; i++) {
                var c = components[i];
                if (c.types && c.types.indexOf('country') >= 0) {
                    // long_name contains country long name and 'short_name' contains country's abbreviated name
                    console.log(c.long_name + '/' + c.short_name);
                    break;
                }
            }                    
        });
    });
});
</script>
</head>

<body>
    <input type="button" id="btn1" value="Load Data" />
</body>

Upvotes: 0

Konza
Konza

Reputation: 2173

pass the url which returns the json to the getJSON function. the parameter data will hold the response json which you got from the server.

You can see that it contains a field named "results" which is an array. So take data.results[0] . Inside that the field formatted_address contains your value.

var url = "https://maps.googleapis.com/maps/api/geocode/json?address=New%20York,%20NY,%20United%20States&sensor=true"  

$.getJSON(url, function(data)
 {
         alert(data.results[0].formatted_address)

 });

Upvotes: 2

Ravikumar Sharma
Ravikumar Sharma

Reputation: 3740

Change your code as below

$(document).ready(function() {
     $("#btn1 ").click(function(event) {
       var address=encodeURI($('#userInput').val());
       var url='https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=true';
       $.getJSON(url, function(data){
          var shortname=data.results[0].address_components[2].short_name
          var longname=data.results[0].address_components[2].long_name
          alert(shortname+' '+longname);
     });
   });
});

Upvotes: 0

JohnnyJS
JohnnyJS

Reputation: 1472

<html>  
<head></head>
<title>Project 9</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&libraries=places"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
 $(document).ready(function() {
 $("#btn1 ").click(function(event) {
url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + 
encodeURI($('#userInput').val()) + '&sensor=true';
 $.getJSON(url, function(data)
 {
     //here we process the json. and whatever we want after the call came back from api
     // notice the data arg that i putted above.
alert(data.results[0].address_components[2].short_name);
// this will alert "US"

 });
 });
 });
</script>         
<body>
<input type="text" value="New York, NY, United States" name="userInput" id="userInput" />
  <input type="button" id="btn" value="Load Data" />
</body>

Cheers.

Upvotes: 2

Related Questions