从给定城市名称获取经度和纬度的简易API

时间:2012-02-27 01:32:31

标签: jquery json api google-api latitude-longitude

我希望我的访客输入城市名称然后我可以从该名称获得经度和纬度。我无法弄清楚如何使用谷歌地图api获取它们。我发现世界天气在线api很容易,所以我有这个json响应,但无法通过它。

{ "search_api" : {
    "result" : [
      { "areaName"   : [ { "value" : "New York" } ], 
        "country"    : [ { "value" : "United States Of America" } ],
        "latitude"   : "40.710",
        "longitude"  : "-74.010", 
        "population" : "8107916",  
        "region"     : [ { "value" : "New York" } ], 
        "weatherUrl" : [ { "value": "http:\/\/free.worldweatheronline.com\/weather\/United-States-Of-America\/2395340\/New-York\/2478232\/info.aspx" } ]
      }, 
      { "areaName"   : [ { "value" : "New York" } ],
        "country"    : [ { "value" : "United States Of America" } ],
        "latitude"   : "32.170",
        "longitude"  : "-95.670",
        "population" : "0",
        "region"     : [ { "value" : "Texas" } ],
        "weatherUrl" : [ { "value": "http:\/\/free.worldweatheronline.com\/weather\/United-States-Of-America\/2395340\/New-York\/2516758\/info.aspx" } ]
      }
    ]
  }
}

这就是我的尝试:

$.getJSON(url, function(data) {
  var cord = data.search_api.latitude;

  alert(cord);
} );

有人可以帮我解决这个问题,还是给我一个更好的方法来获取某个城市名称或地址的经度和纬度?

1 个答案:

答案 0 :(得分:0)

您的代码无效,因为当您需要首先浏览名为search_api的数组时,您尝试直接从latitude跳转到result,例如

$.getJSON( url, function( data ) {
  var firstResult = data.search_api.result[ 0 ];

  console.log( "City:",      firstResult.areaName[ 0 ].value, ",",
                             firstResult.region[ 0 ].value
  );
  console.log( "Latitude:",  firstResult.latitude );
  console.log( "Longitude:", firstResult.longitude );
} );

/* Output:
   > City: New York , New York
   > Latitude: 40.710
   > Longitude: -74.010
*/