地理位置api
Update long overdue -- the Geolocation API is now available in all browsers!
逾期未更新-现在所有浏览器都可使用Geolocation API!
![Mozilla Firefox Geolocation](https://i-blog.csdnimg.cn/blog_migrate/a8f916d4916a8f9007f3d358463b3c7e.png)
One interesting aspect of web development is geolocation; where is your user viewing your website from? You can base your language locale on that data or show certain products in your store based on the user's location. Let's examine how you can use the geolocation API to get location details!
Web开发的一个有趣方面是地理位置。 您的用户从哪里查看您的网站? 您可以根据该数据选择语言区域设置,也可以根据用户的位置在商店中显示某些产品。 让我们研究如何使用geolocation API获取位置详细信息!
检测浏览器地理位置功能 (Detecting Browser Geolocation Capabilities)
Feature detection is the best way to confirm the Geolocation API is avilable.
功能检测是确认Geolocation API适用的最佳方法。
if("geolocation" in navigator) {
//w00t!
}
else {
alert("No soup for you! Your browser does not support this feature");
}
They key to detecting Geolocation within your browser is the navigator.geolocation
object. Use in
instead of simply if(navigator.geolocation)
is important because that check may initialize geolocation and take up device resources.
它们是在浏览器中检测Geolocation的关键是navigator.geolocation
对象。 使用in
而不是简单地使用if(navigator.geolocation)
很重要,因为该检查可能会初始化地理位置并占用设备资源。
查询地理位置信息 (Querying For Geolocation Information)
The navigator.geolocation.getCurrentPosition
method is the driving force behind retrieving location details:
navigator.geolocation.getCurrentPosition
方法是检索位置详细信息的驱动力:
if("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function(position) {
console.log(position);
});
}
Once you call this method (providing it a function which will execute if your request is successful), the browser will ask the user if they will allow you to retrieve their location information:
调用此方法(为它提供一个在请求成功后将执行的功能),浏览器将询问用户是否允许您检索其位置信息:
When the user allows the website to retrieve their location information, the browser fetches the information, providing you a position object with a payload that looks like:
当用户允许网站检索其位置信息时,浏览器将获取该信息,为您提供一个具有有效负载的位置对象,如下所示:
// "Position" object
{
coords: { "Coordinates" object
accuracy: 65,
altitude: 294.4074401855469,
altitudeAccuracy: 10,
heading: -1,
latitude: 43.01256284360166,
longitude: -89.44531987692744,
speed: -1
},
timestamp: 1429722992094269
}
If you want more information like country, city, and so on, you can use a third party service -- there are many out there.
如果您想要国家,城市等更多信息,则可以使用第三方服务-那里有很多服务。
This API is the foundation of many mobile apps and really should be in the toolbox of any web developer. Best yet is that all browsers now support the Geolocation API. Happy coding!
该API是许多移动应用程序的基础,实际上应该在任何Web开发人员的工具箱中。 最好的是,所有浏览器现在都支持Geolocation API。 编码愉快!
地理位置api