javascript - 从谷歌地图请求中解析城市/州

标签 javascript parsing google-maps-api-3

var geocoder = new google.maps.Geocoder();
            geocoder.geocode({'latLng': foundLoc}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        var loc = getCityState(results);
                    }
                }
            }); 

function getCityState(results)
        {
            var citystateArray = results[1].formatted_address.split(",",2);
            var city = citystateArray[0];
            var state = citystateArray[1].substring(1, 3);
            return (city + ', ' + state)
        }

这就是我现在使用的,并且大约 90% 的时间都有效。其他时候,formatted_address 包含城镇和城市以及州,其他时候只是城镇和城市,其他时候您可以梦想的一切。

我还没有找到始终如一的方法来从 Google Maps API 结果中获取城市/州。你们中有人有吗?谢谢。

Google 在其页面上用作示例的一个响应示例:

{
  "status": "OK",
  "results": [ {
    "types": [ "street_address" ],
    "formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
    "address_components": [ {
      "long_name": "1600",
      "short_name": "1600",
      "types": [ "street_number" ]
    }, {
      "long_name": "Amphitheatre Pkwy",
      "short_name": "Amphitheatre Pkwy",
      "types": [ "route" ]
    }, {
      "long_name": "Mountain View",
      "short_name": "Mountain View",
      "types": [ "locality", "political" ]
    }, {
      "long_name": "California",
      "short_name": "CA",
      "types": [ "administrative_area_level_1", "political" ]
    }, {
      "long_name": "United States",
      "short_name": "US",
      "types": [ "country", "political" ]
    }, {
      "long_name": "94043",
      "short_name": "94043",
      "types": [ "postal_code" ]
    } ],
    "geometry": {
      "location": {
        "lat": 37.4219720,
        "lng": -122.0841430
      },
      "location_type": "ROOFTOP",
      "viewport": {
        "southwest": {
          "lat": 37.4188244,
          "lng": -122.0872906
        },
        "northeast": {
          "lat": 37.4251196,
          "lng": -122.0809954
        }
      }
    }
  } ]
}

有时这些字段没有值,有时它们有。

最佳答案

为什么要解析 formatted_address

有 address_components,你可以遍历它们并寻找带有

"types": [ "administrative_area_level_1", "political" ]// the state
"types" : [ "locality", "political" ]//the city

这是一个例子:http://jsfiddle.net/doktormolle/QWPCL/

关于javascript - 从谷歌地图请求中解析城市/州,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6542788/

相关文章:

javascript - GUI 线程无法使用 jQuery 正确更新

javascript - Google map 自定义数据层在缩放时不触发

javascript - jquery 调整大小丢失 'this' 引用

javascript - AJAX中setTimeout函数的使用

ruby - 在使用 Ruby 连接到 HTTPS url 并将源数据传递给 Nokogiri 方面需要帮助

python - 如何通过 python 从 mediawiki 标记的文章中解析/提取数据

javascript - Google 使用自定义标记和 OnClick 缩放来映射多个标记

javascript - 高精度地理定位 Html5

javascript - 如何自定义 Bootstrap JS Popover

iphone - iOS CXMLElement 字符串值