最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Call JSON element from an API and return result as string - Stack Overflow

programmeradmin2浏览0评论

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:
;libraries=places

Desired Result:
United States/US/USA

JSON something not sure what it's called:
,%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=";libraries=places"></script>
<script src=".10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
     $("#btn1 ").click(function() {
       var address=encodeURI($('#userInput').val());
       var url='='+address+'&sensor=true';
       $.getJSON(url, function(data){
          var shortname=data.results[0].address_ponents[3].short_name;
          var longname=data.results[0].address_ponents[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_ponents how can we limit it to return only the country? thanks

Could it work like this?

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

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./maps/api/js?sensor=true&libraries=places

Desired Result:
United States/US/USA

JSON something not sure what it's called:
https://maps.googleapis./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./maps/api/js?sensor=true&libraries=places"></script>
<script src="http://code.jquery./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./maps/api/geocode/json?address='+address+'&sensor=true';
       $.getJSON(url, function(data){
          var shortname=data.results[0].address_ponents[3].short_name;
          var longname=data.results[0].address_ponents[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_ponents how can we limit it to return only the country? thanks

Could it work like this?

  var shortname=data.results[0].address_ponents[country].short_name;
  var longname=data.results[0].address_ponents[country].long_name;
  alert(shortname+' '+longname);
Share Improve this question edited Feb 12, 2014 at 9:42 Mr. Fox asked Feb 12, 2014 at 8:54 Mr. FoxMr. Fox 3181 gold badge7 silver badges28 bronze badges 1
  • Marking an answer as correct will help others as well. :) – Konza Commented Feb 12, 2014 at 10:30
Add a ment  | 

5 Answers 5

Reset to default 2

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./maps/api/geocode/json?address=New%20York,%20NY,%20United%20States&sensor=true"  

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

 });
<html>  
<head></head>
<title>Project 9</title>
<script type="text/javascript" src="http://maps.google./maps/api/js?sensor=true&libraries=places"></script>
<script src="http://code.jquery./jquery-1.10.1.min.js"></script>
<script type="text/javascript">
 $(document).ready(function() {
 $("#btn1 ").click(function(event) {
url = "https://maps.googleapis./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_ponents[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.

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./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_ponents);

        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
        */

    }
})

Change your code as below

$(document).ready(function() {
     $("#btn1 ").click(function(event) {
       var address=encodeURI($('#userInput').val());
       var url='https://maps.googleapis./maps/api/geocode/json?address='+address+'&sensor=true';
       $.getJSON(url, function(data){
          var shortname=data.results[0].address_ponents[2].short_name
          var longname=data.results[0].address_ponents[2].long_name
          alert(shortname+' '+longname);
     });
   });
});
<html>  
<head>
<title>Project 9</title>
<script type="text/javascript" src="http://maps.google./maps/api/js?sensor=true&libraries=places"></script>
<script src="http://code.jquery./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./maps/api/geocode/json?sensor=true';
        var data = { address: 'New York,NY,United States'};
        $.getJSON(url, data, function (result) {
            var ponents = result.results[0].address_ponents;
            for (var i = 0; i < ponents.length; i++) {
                var c = ponents[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>

发布评论

评论列表(0)

  1. 暂无评论