首页 > 解决方案 > 如何使用谷歌地理编码 API 从地址获取纬度和经度?

问题描述

创建一个天气应用程序来学习 JavaScript。当页面根据纬度和经度加载时,我已经设法从 OpenWeatherMap API 获取计算机位置的天气,然后我有一个使用谷歌地点 API 自动填充的下拉框,然后我有一个提交按钮,我想将地点名称转换为纬度和经度,以从 OpenWeatherMap 获取新位置的天气。我不知道要从结果中得出什么。

第一:JSON数据:

   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Tbilisi",
               "short_name" : "Tbilisi",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Didi digomi",
               "short_name" : "Didi digomi",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Tbilisi",
               "short_name" : "Tbilisi",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "Georgia",
               "short_name" : "GE",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Tbilisi, Georgia",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 41.8438937,
                  "lng" : 45.0176811
               },
               "southwest" : {
                  "lat" : 41.6210248,
                  "lng" : 44.6600246
               }
            },
            "location" : {
               "lat" : 41.7151377,
               "lng" : 44.827096
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 41.8438937,
                  "lng" : 45.0176811
               },
               "southwest" : {
                  "lat" : 41.6210248,
                  "lng" : 44.6600246
               }
            }
         },
         "place_id" : "ChIJa2JP5tcMREARo25X4u2E0GE",
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
} 

然后是我的代码,我可以在其中获得 STATUS 罚款,但我不知道如何更改它以获得纬度和经度:


var request = new XMLHttpRequest();

                request.open('GET',link,true);
                request.onload = function(){
                var obj2 = JSON.parse(this.response);
                if (request.status >= 200 && request.status < 400) {

                var newLat = (obj2.status);
                document.write(obj2.status);
               // var newLng = (obj2.results.formatted_address);
                alert(newLat);

这会导致“OK”警报,并且文档上写着“OK”,但是当我尝试更改它以提取纬度和经度数据时,它吓坏了。

请帮忙。

标签: javascriptgoogle-geocoding-api

解决方案


推荐阅读