js 获取当前位置城市
时间: 2023-11-22 11:39:25 浏览: 30
您好,可以使用 HTML5 的 Geolocation API 来获取当前位置的经纬度,然后通过逆地理编码 API 将经纬度解析成具体的城市名称。具体实现可以参考以下代码:
```javascript
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var url = "https://api.mapbox.com/geocoding/v5/mapbox.places/" + longitude + "," + latitude + ".json?access_token=YOUR_ACCESS_TOKEN";
fetch(url)
.then(function(response) {
return response.json();
})
.then(function(data) {
var city = data.features[0].context[1].text;
console.log("当前位置城市:" + city);
});
});
} else {
console.log("Geolocation is not supported by this browser.");
}
```
需要注意的是,代码中的 YOUR_ACCESS_TOKEN 需要替换成您自己的 Mapbox Access Token。