如何使用Facebook Graph API获取用户所在国家?

17

我想获取已登录用户的国家,并将其插入到一个

中。 我已成功使用用户姓名、性别和年龄范围进行设置,但不知何故无法检索国家。 以下是我的代码:

  function testAPI() {
console.log('Welcome!  Fetching your information.... ');
FB.api('/me?fields=name,email,gender,age_range,picture,country', function (response) {
  document.getElementById('status').innerHTML = response.name + ",";
  document.getElementById('status1').innerHTML = response.gender + ",";
  document.getElementById('status2').innerHTML = (response.age_range.min) + "-" + (response.age_range.min + 1) + " years old";
  document.getElementById('status3').innerHTML = response.country;
}

谢谢!


请查看以下链接:http://stackoverflow.com/questions/27379382/retrieve-user-country-through-facebook-android-graph-api - Esty
4个回答

53

为了补充Lix所说的:

您可以通过一次Graph API调用来完成,调用:

/me?fields=name,email,gender,age_range,picture,location{location}

实际上,在用户对象下面的位置对象是一个页面对象,它有一个位置对象

这将给你类似这样的东西:

"location": {
  "location": {
    "city": "Ramat Gan",
    "country": "Israel",
    "latitude": 32.0833,
    "longitude": 34.8167,
    "zip": "<<not-applicable>>"
  }
}

这样可以避免您对Graph API进行两次调用。


location{location}对我来说是新的语法 - 显然我还没有接触到这些变化 - 你能否请多解释一下它的用法? - Lix
很抱歉,我不明白如何在使用上添加更多的解释... 有什么你没理解的地方吗? - vchabot
所以我理解这里我们尝试了“我”,但我能否在那里提供用户ID并获得相同的结果? - Hima Varsha
1
我认为这个 location{location} 是旧语法。如果有人在 2017 年对此感到困惑,那么对我有效的是:location.fields(location)。请参阅此主题以获取更多详细信息:https://stackoverflow.com/a/29274998/2561091 - Reuel Ribeiro
状态在哪里? - Pratik Butani

29

我相信你要寻找的参数是 location 而不是 country。

/me?fields=name,email,gender,age_range,picture,location
为了查询这些数据,你需要让你的用户授予你user_location权限。 这将给你用户提交字段的值 - 请注意,由于它取决于用户是否提供了此信息,所以该参数可能并不总是有值 - 如果他们没有提供,你将无法检索到它。
对象的外观类似于这样:
  "location": {
    "id": "112604772085346",
    "name": "Ramat Gan"
  },

一旦您有了位置对象(很可能是页面),您可以查询该对象以检索国家:

/112604772085346?fields=location

这将为您提供更多信息,包括国家。

{
  "location": {
    "city": "Ramat Gan",
    "country": "Israel",
    "latitude": 32.0833,
    "longitude": 34.8167,
    "zip": "<<not-applicable>>"
  },
  "id": "112604772085346"
}

看一下vchatbot的回答,@Idan - 看起来有一种方法可以只使用一个API请求来完成这个操作 - 更好:P - Lix
在Facebook上获取国家的ISO代码是可能的吗?https://en.wikipedia.org/wiki/ISO_3166-1 - user1253414
@user1253414 - 我认为Facebook不提供ISO代码的国家。您可能需要使用额外的步骤来进行转换 - 或许像这样的东西可以帮助您 - https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes - Lix
@Lix 针对您的评论,尽管这个来源非常好,但我发现有大约40个没有提供国家名称。因此,仅凭名称匹配还是有点棘手的工作。 - Billy Jake O'Connor

2

Fb API中的字段现在可以连接起来使用,因此,要获取用户位置的详细信息,您需要:

scope="public_profile,user_location"

fields="name,location{location{country, country_code, city, city_id, latitude, longitude, region, region_id, state, street, name}}"

错误:尝试访问不存在的字段(user_location) - Mohamad Hamouday

0

v2.11 查询:

/me?fields=hometown,location

权限:

user_hometown
user_location

结果:

{
  "hometown": {
    "id": "XXXXREDACTED",
    "name": "Manila, Philippines"
  },
  "location": {
    "id": "XXXXREDACTED",
    "name": "Manila, Philippines"
  },
  "id": "XXXXREDACTED"
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接