通过地理位置获取用户的状态 [英] Get a user's State with Geolocation

查看:95
本文介绍了通过地理位置获取用户的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取美国用户的国家最有效的方式是什么? HTML5地理定位是一个不需要涉及谷歌地图的选项吗?

这里有几个JavaScript和JSON示例的 jQuery )同时使用IP查找方法(借助 IPinfoDB )和 Geolocation API 方法(借助Google Maps API YQL )。



在这两个示例中,我都会检索该地区和国家,但有几个值可供您选择。请注意,这些示例不会执行任何错误处理,并且为了简洁起见,这些示例都进行了编辑,否则请参阅完整演示

JavaScript中的IP查找



这种方法很好,因为它很容易实现,一个国家的水平,但准确性大幅下降,更具体的东西。

  //为简洁起见排除API密钥,请参阅完整演示。 
var apiurl ='http://api.ipinfodb.com/v3/ip-city';
$ .getJSON(apiurl +'/ format = json& callback =?',
function(data){
$(h3#location)。html(data.regionName +, + data.countryName);
}
);



地理定位API



尽管完美,这种方法是一样准确的。

  navigator.geolocation.getCurrentPosition(function(pos){
$ .getJSON(apiurl +'/ format = json& callback =?',
function(data){
var regionName = data [...] AdministrativeAreaName;
var countryName = data [ ...] CountryName;
$(h3#location)。html(regionName +,+ countryName);
}
);
});

在那里您会看到我使用了 Google Maps API v3 ,方法是 YQL ,以便JSON回调是可能的。



完整演示: http://jsfiddle.net/ZjXXh


What's the most efficient way to get a United States user's State? Is HTML5 Geolocation an option without needing to involve google maps?

解决方案

Here's a couple of examples in JavaScript and JSON (with the help of jQuery) using both the IP lookup method (with the help of IPinfoDB) and the Geolocation API method (with the help of Google Maps API and YQL).

In both examples I'm retrieving the region and country but there are several values you can choose from. Be aware these examples don't do any error handling and here they are edited for brevity, otherwise see the full demo.

IP Lookup in JavaScript

This method is good because it's easy to implement and is fairly accurate at a country level but accuracy drops considerably for anything more specific.

// API key excluded for brevity, see full demo.
var apiurl = 'http://api.ipinfodb.com/v3/ip-city';
$.getJSON(apiurl+'/format=json&callback=?',
    function(data){
        $("h3#location").html(data.regionName + ", " + data.countryName);
    }
);

Geolocation API

Although by no means perfect, this method is as accurate as it gets. User is prompted to share geolocation details which may reduce usage.

navigator.geolocation.getCurrentPosition(function(pos){
    $.getJSON(apiurl+'/format=json&callback=?',
        function(data){
            var regionName = data[...]AdministrativeAreaName;
            var countryName = data[...]CountryName;
            $("h3#location").html(regionName + ", " + countryName);
        }
    );
});

In there you'll see I used the Google Maps API v3 by way of YQL so that a JSON callback is possible.

Full demo: http://jsfiddle.net/ZjXXh

这篇关于通过地理位置获取用户的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆