使用 JavaScript 获取用户位置
在本教程中,我将向您展示如何使用 JavaScript 地理位置 API 获取用户的位置。
您可以使用它将他们重定向到他们语言的网站或新闻或天气应用程序等网站,并使用他们的位置来调整主页以显示与他们所在位置相关的内容。
本文最初是一个视频教程,您可以在这里查看:
检查导航器 API 是否可用
地理位置功能是window
对象的一部分,可以通过window.navigator.geolocation
或简单地访问navigator.geolocation
。
一些老版本的浏览器可能不支持地理位置 API,因此在使用它之前应该使用 if 语句检查它是否存在:
if (navigator.geolocation) {
/* use the API here */
}
获取用户的坐标
如果您的浏览器支持该 API,您可以使用其方法。获取用户坐标的方法是navigator.geolocation.getCurrentPosition
。
它需要作为参数,一个成功回调和一个可选的错误回调和选项。
为了测试它,我们可以使用它console.log
作为成功回调函数和console.error
错误回调。
根据调用是否成功,这两个函数之一将被调用。
window.navigator.geolocation
.getCurrentPosition(console.log, console.error);
首次使用时,系统将提示用户允许该网站访问其位置。
一旦授予权限,您应该在 JavaScript 控制台中看到类似这样的内容:
/* GeolocationPosition */
{
/* GeolocationCoordinates */
"coords": {
"accuracy": 1000,
"altitude": null,
"altitudeAccuracy": null,
"heading": null,
"latitude": 39.7501,
"longitude": -104.9957,
"speed": null
},
"timestamp": 1608826371767
}
您将拥有一个GeolocationPosition
包含GeolocationCoordinates
标记为的对象coords
和时间戳的对象。
成功函数
除了使用之外console.log
,您还可以使用自定义成功回调来对数据执行您需要的操作。
function success(data) {
// extracting the latitude and longitude from the data
let latitude = data.coords.latitude;
let longitude = data.coords.longitude;
alert("Your location: " + latitude + ", " + longitude);
}
if (navigator.geolocation) {
window.navigator.geolocation
.getCurrentPosition(success, console.error);
}
这将告诉函数在成功查找位置时getCurrentPosition
调用并将地理位置位置作为参数发送。success
上述函数success
将提取纬度和经度并弹出窗口告知用户。
如果您想知道他们的城市或国家怎么办?
如果您想以更有意义的方式了解用户所在的位置,您可以使用反向地理编码 API 进行查找。
有很多 API 可以实现这一点。在本教程中,我使用了 OpenCage API。
在opencagedata.com创建一个免费帐户并获取可用于您的应用程序的 API 密钥。
您可以在其JavaScript 文档中找到使用 OpenCage 进行反向地理编码的代码片段。
我们可以使用现代 JavaScript 技术来简化它:
let apikey = "your API key goes here";
let latitude = '51.0';
let longitude = '7.0';
fetch('https://api.opencagedata.com/geocode/v1/json'
+ '?'
+ 'key=' + apikey
+ '&q=' + encodeURIComponent(latitude + ',' + longitude)
+ '&pretty=1'
+ '&no_annotations=1')
.then((response) => response.json())
.then((data) => alert(data.results[0].formatted));
假设你拥有 OpenCage 的有效 API 密钥,上面的代码片段应该会发出一条警告,内容是“Grüner Kuhweg, 51061 Cologne, Germany”。这就是坐标 51.0, 7.0 对应的位置。
如果您data.results[0]
登录控制台,您将看到除了可以访问的格式化地址之外还有几个字段:
{
"bounds": {
"northeast": {
"lat": 51.0008597,
"lng": 7.0042934
},
"southwest": {
"lat": 50.9973232,
"lng": 6.999946
}
},
"components": {
"ISO_3166-1_alpha-2": "DE",
"ISO_3166-1_alpha-3": "DEU",
"_category": "road",
"_type": "road",
"city": "Cologne",
"city_district": "Mülheim",
"continent": "Europe",
"country": "Germany",
"country_code": "de",
"political_union": "European Union",
"postcode": "51061",
"road": "Grüner Kuhweg",
"road_type": "service",
"state": "North Rhine-Westphalia",
"state_code": "NW",
"suburb": "Flittard"
},
"confidence": 9,
"formatted": "Grüner Kuhweg, 51061 Cologne, Germany",
"geometry": {
"lat": 50.999559,
"lng": 7.0002524
}
}
访问特定组件
您可以访问返回的 JSON 对象的任何组件。
要访问用户的城市,我们可以说data.results[0].components.city
。
为了得到他们的国家,我们可以说data.results[0].components.country
。
对用户位置进行反向地理编码
现在我们可以访问用户的坐标和反向地理编码坐标,我们可以将它们放在一起:
function reverseGeocode(latitude, longitude) {
let apikey = "your API key goes here";
fetch('https://api.opencagedata.com/geocode/v1/json'
+ '?'
+ 'key=' + apikey
+ '&q=' + encodeURIComponent(latitude + ',' + longitude)
+ '&pretty=1'
+ '&no_annotations=1')
.then((response) => response.json())
.then((data) => alert(data.results[0].formatted));
}
function success(data) {
// extracting the latitude and longitude from the data
let latitude = data.coords.latitude;
let longitude = data.coords.longitude;
// reverse geocode
reverseGeocode(latitude, longitude);
}
if (navigator.geolocation) {
window.navigator.geolocation
.getCurrentPosition(success, console.error);
}
通话结束时的警报功能reverseGeocode
可以替换为您需要使用数据的任何功能。
在我的视频“使用 JavaScript 获取用户的位置”中,我展示了如何在天气应用中使用它来显示用户当前位置的天气。
结论
我希望您发现本教程很有用。
观看视频了解更多解释,并务必点赞和订阅!
- 乔纳·劳伦斯
YouTube:Jonah Lawrence - Dev Pro Tips
文章来源:https://dev.to/denvercoder1/getting-the-user-s-location-with-javascript-47m0