首页 文章

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

提问于
浏览
0

我希望我的访客输入一个城市名称然后我可以从该名称获得经度和纬度 . 我无法弄清楚如何使用谷歌 Map 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

    您的代码不起作用,因为当您需要首先通过名为 result 的数组时,您尝试直接从 search_api 跳到 latitude ,例如

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

相关问题