有什么方法可以从Google Maps自动完成api中检测国家/地区电话代码吗?

时间:2018-10-25 07:30:08

标签: google-maps google-maps-api-3 google-maps-autocomplete

我正在构建一个Web应用程序,该应用程序需要存储客户端的位置以及电话号码。我希望在选择位置后自动检测电话代码。我已经仔细阅读了以下链接中提供的Google地图文档,但没有运气。 Google Maps Documentation 。有什么方法可以从Google地图位置检测电话代码?

1 个答案:

答案 0 :(得分:0)

确定了国家/地区之后,您可以访问https://restcountries.eu之类的外部API并检索有关任何国家/地区的数据(包括电话代码)。

例如https://restcountries.eu/rest/v2/name/nepal?fullText=true返回此JSON,您可以在其中看到callingCodes = 997

[{
    "name": "Nepal",
    "topLevelDomain": [".np"],
    "alpha2Code": "NP",
    "alpha3Code": "NPL",
    "callingCodes": ["977"],
    "capital": "Kathmandu",
    "altSpellings": ["NP", "Federal Democratic Republic of Nepal", "Loktāntrik Ganatantra Nepāl"],
    "region": "Asia",
    "subregion": "Southern Asia",
    "population": 28431500,
    "latlng": [28.0, 84.0],
    "demonym": "Nepalese",
    "area": 147181.0,
    "gini": 32.8,
    "timezones": ["UTC+05:45"],
    "borders": ["CHN", "IND"],
    "nativeName": "नेपाल",
    "numericCode": "524",
    "currencies": [{
        "code": "NPR",
        "name": "Nepalese rupee",
        "symbol": "₨"
    }],
    "languages": [{
        "iso639_1": "ne",
        "iso639_2": "nep",
        "name": "Nepali",
        "nativeName": "नेपाली"
    }],
    "translations": {
        "de": "Népal",
        "es": "Nepal",
        "fr": "Népal",
        "ja": "ネパール",
        "it": "Nepal",
        "br": "Nepal",
        "pt": "Nepal",
        "nl": "Nepal",
        "hr": "Nepal",
        "fa": "نپال"
    },
    "flag": "https://restcountries.eu/data/npl.svg",
    "regionalBlocs": [{
        "acronym": "SAARC",
        "name": "South Asian Association for Regional Cooperation",
        "otherAcronyms": [],
        "otherNames": []
    }],
    "cioc": "NEP"
}]

编辑:根据要求添加了代码。

<html>
<body>
<h2>Get the phone code for Napal</h2>

<button type="button" onclick="loadDoc()">Get Phone Code</button>

<p id="demo"></p>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var locObj =  JSON.parse(this.responseText);
      document.getElementById("demo").innerHTML = "Phone Code for Napal = "+locObj[0].callingCodes;
    }
  };
  xhttp.open("GET", "https://restcountries.eu/rest/v2/name/nepal?fullText=true", true);
  xhttp.send();
}
</script>

</body>
</html>

产生此输出:

Phone Code for Napal = 977