从API调用JSON元素并将结果作为字符串返回

时间:2014-02-12 08:54:39

标签: javascript jquery json google-maps

我正在尝试从API调用一个特定(国家/地区)的元素,我希望它以字符串形式返回,我将在下面详细说明

用户的输入:
纽约,纽约,美国

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

期望的结果:
美国/美国/美国

JSON不确定它叫什么:
https://maps.googleapis.com/maps/api/geocode/json?address=New%20York,%20NY,%20United%20States&sensor=true

我对如何做到这一点有点迷失,但这是我尝试过的:

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

我更新了这个问题,我很欣赏你的所有答案,但是我注意到在某些输入中,它不会返回国家但是返回address_components的索引3中的对象我们怎样才能限制它只返回国家?感谢

它可以像这样工作吗?

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

5 个答案:

答案 0 :(得分:2)

将返回json的url传递给getJSON函数。参数数据将保存您从服务器获得的响应json。

你可以看到它包含一个名为&#34的字段;结果&#34;这是一个数组。所以请参考data.results [0]。在其中,formatted_address字段包含您的值。

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)

 });

答案 1 :(得分:2)

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

干杯。

答案 2 :(得分:1)

首先,阅读这篇文章。

getJSON 签名如下:

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

回调功能签名如下:

callback( data, textStatus, jqXHR );
  • 数据是所需的json对象
  • textStatus是一个用于检查ajax请求状态的字符串
  • jqXHR是实际的ajax请求对象

因此,如果您要将数据作为查询字符串发送,例如地址作为参数,则可以将其发送为:

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

    }
})

答案 3 :(得分:0)

更改您的代码如下

$(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);
     });
   });
});

答案 4 :(得分:0)

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